home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / guile / 1.8 / ice-9 / boot-9.scm < prev    next >
Encoding:
Text File  |  2008-12-17  |  101.7 KB  |  3,479 lines

  1. ;;; installed-scm-file
  2.  
  3. ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007
  4. ;;;; Free Software Foundation, Inc.
  5. ;;;;
  6. ;;;; This library is free software; you can redistribute it and/or
  7. ;;;; modify it under the terms of the GNU Lesser General Public
  8. ;;;; License as published by the Free Software Foundation; either
  9. ;;;; version 2.1 of the License, or (at your option) any later version.
  10. ;;;; 
  11. ;;;; This library is distributed in the hope that it will be useful,
  12. ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14. ;;;; Lesser General Public License for more details.
  15. ;;;; 
  16. ;;;; You should have received a copy of the GNU Lesser General Public
  17. ;;;; License along with this library; if not, write to the Free Software
  18. ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. ;;;;
  20.  
  21.  
  22.  
  23. ;;; Commentary:
  24.  
  25. ;;; This file is the first thing loaded into Guile.  It adds many mundane
  26. ;;; definitions and a few that are interesting.
  27. ;;;
  28. ;;; The module system (hence the hierarchical namespace) are defined in this
  29. ;;; file.
  30. ;;;
  31.  
  32. ;;; Code:
  33.  
  34.  
  35.  
  36. ;;; {Features}
  37. ;;;
  38.  
  39. (define (provide sym)
  40.   (if (not (memq sym *features*))
  41.       (set! *features* (cons sym *features*))))
  42.  
  43. ;; Return #t iff FEATURE is available to this Guile interpreter.  In SLIB,
  44. ;; provided? also checks to see if the module is available.  We should do that
  45. ;; too, but don't.
  46.  
  47. (define (provided? feature)
  48.   (and (memq feature *features*) #t))
  49.  
  50. ;; let format alias simple-format until the more complete version is loaded
  51.  
  52. (define format simple-format)
  53.  
  54. ;; this is scheme wrapping the C code so the final pred call is a tail call,
  55. ;; per SRFI-13 spec
  56. (define (string-any char_pred s . rest)
  57.   (let ((start (if (null? rest)
  58.            0 (car rest)))
  59.     (end   (if (or (null? rest) (null? (cdr rest)))
  60.            (string-length s) (cadr rest))))
  61.     (if (and (procedure? char_pred)
  62.          (> end start)
  63.          (<= end (string-length s))) ;; let c-code handle range error
  64.     (or (string-any-c-code char_pred s start (1- end))
  65.         (char_pred (string-ref s (1- end))))
  66.     (string-any-c-code char_pred s start end))))
  67.  
  68. ;; this is scheme wrapping the C code so the final pred call is a tail call,
  69. ;; per SRFI-13 spec
  70. (define (string-every char_pred s . rest)
  71.   (let ((start (if (null? rest)
  72.            0 (car rest)))
  73.     (end   (if (or (null? rest) (null? (cdr rest)))
  74.            (string-length s) (cadr rest))))
  75.     (if (and (procedure? char_pred)
  76.          (> end start)
  77.          (<= end (string-length s))) ;; let c-code handle range error
  78.     (and (string-every-c-code char_pred s start (1- end))
  79.          (char_pred (string-ref s (1- end))))
  80.     (string-every-c-code char_pred s start end))))
  81.  
  82. ;; A variant of string-fill! that we keep for compatability
  83. ;;
  84. (define (substring-fill! str start end fill)
  85.   (string-fill! str fill start end))
  86.  
  87.  
  88.  
  89. ;;; {EVAL-CASE}
  90. ;;;
  91.  
  92. ;; (eval-case ((situation*) forms)* (else forms)?)
  93. ;;
  94. ;; Evaluate certain code based on the situation that eval-case is used
  95. ;; in.  The only defined situation right now is `load-toplevel' which
  96. ;; triggers for code evaluated at the top-level, for example from the
  97. ;; REPL or when loading a file.
  98.  
  99. (define eval-case
  100.   (procedure->memoizing-macro
  101.    (lambda (exp env)
  102.      (define (toplevel-env? env)
  103.        (or (not (pair? env)) (not (pair? (car env)))))
  104.      (define (syntax)
  105.        (error "syntax error in eval-case"))
  106.      (let loop ((clauses (cdr exp)))
  107.        (cond
  108.     ((null? clauses)
  109.      #f)
  110.     ((not (list? (car clauses)))
  111.      (syntax))
  112.     ((eq? 'else (caar clauses))
  113.      (or (null? (cdr clauses))
  114.          (syntax))
  115.      (cons 'begin (cdar clauses)))
  116.     ((not (list? (caar clauses)))
  117.      (syntax))
  118.     ((and (toplevel-env? env)
  119.           (memq 'load-toplevel (caar clauses)))
  120.      (cons 'begin (cdar clauses)))
  121.     (else
  122.      (loop (cdr clauses))))))))
  123.  
  124.  
  125.  
  126. ;;; {Defmacros}
  127. ;;;
  128. ;;; Depends on: features, eval-case
  129. ;;;
  130.  
  131. (define macro-table (make-weak-key-hash-table 61))
  132. (define xformer-table (make-weak-key-hash-table 61))
  133.  
  134. (define (defmacro? m)  (hashq-ref macro-table m))
  135. (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
  136. (define (defmacro-transformer m) (hashq-ref xformer-table m))
  137. (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
  138.  
  139. (define defmacro:transformer
  140.   (lambda (f)
  141.     (let* ((xform (lambda (exp env)
  142.             (copy-tree (apply f (cdr exp)))))
  143.        (a (procedure->memoizing-macro xform)))
  144.       (assert-defmacro?! a)
  145.       (set-defmacro-transformer! a f)
  146.       a)))
  147.  
  148.  
  149. (define defmacro
  150.   (let ((defmacro-transformer
  151.       (lambda (name parms . body)
  152.         (let ((transformer `(lambda ,parms ,@body)))
  153.           `(eval-case
  154.         ((load-toplevel)
  155.          (define ,name (defmacro:transformer ,transformer)))
  156.         (else
  157.          (error "defmacro can only be used at the top level")))))))
  158.     (defmacro:transformer defmacro-transformer)))
  159.  
  160. (define defmacro:syntax-transformer
  161.   (lambda (f)
  162.     (procedure->syntax
  163.           (lambda (exp env)
  164.         (copy-tree (apply f (cdr exp)))))))
  165.  
  166.  
  167. ;; XXX - should the definition of the car really be looked up in the
  168. ;; current module?
  169.  
  170. (define (macroexpand-1 e)
  171.   (cond
  172.    ((pair? e) (let* ((a (car e))
  173.              (val (and (symbol? a) (local-ref (list a)))))
  174.         (if (defmacro? val)
  175.             (apply (defmacro-transformer val) (cdr e))
  176.             e)))
  177.    (#t e)))
  178.  
  179. (define (macroexpand e)
  180.   (cond
  181.    ((pair? e) (let* ((a (car e))
  182.              (val (and (symbol? a) (local-ref (list a)))))
  183.         (if (defmacro? val)
  184.             (macroexpand (apply (defmacro-transformer val) (cdr e)))
  185.             e)))
  186.    (#t e)))
  187.  
  188. (provide 'defmacro)
  189.  
  190.  
  191.  
  192. ;;; {Deprecation}
  193. ;;;
  194. ;;; Depends on: defmacro
  195. ;;;
  196.  
  197. (defmacro begin-deprecated forms
  198.   (if (include-deprecated-features)
  199.       (cons begin forms)
  200.       #f))
  201.  
  202.  
  203.  
  204. ;;; {R4RS compliance}
  205. ;;;
  206.  
  207. (primitive-load-path "ice-9/r4rs.scm")
  208.  
  209.  
  210.  
  211. ;;; {Simple Debugging Tools}
  212. ;;;
  213.  
  214. ;; peek takes any number of arguments, writes them to the
  215. ;; current ouput port, and returns the last argument.
  216. ;; It is handy to wrap around an expression to look at
  217. ;; a value each time is evaluated, e.g.:
  218. ;;
  219. ;;    (+ 10 (troublesome-fn))
  220. ;;    => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
  221. ;;
  222.  
  223. (define (peek . stuff)
  224.   (newline)
  225.   (display ";;; ")
  226.   (write stuff)
  227.   (newline)
  228.   (car (last-pair stuff)))
  229.  
  230. (define pk peek)
  231.  
  232. (define (warn . stuff)
  233.   (with-output-to-port (current-error-port)
  234.     (lambda ()
  235.       (newline)
  236.       (display ";;; WARNING ")
  237.       (display stuff)
  238.       (newline)
  239.       (car (last-pair stuff)))))
  240.  
  241.  
  242.  
  243. ;;; {Trivial Functions}
  244. ;;;
  245.  
  246. (define (identity x) x)
  247. (define (and=> value procedure) (and value (procedure value)))
  248. (define call/cc call-with-current-continuation)
  249.  
  250. ;;; apply-to-args is functionally redundant with apply and, worse,
  251. ;;; is less general than apply since it only takes two arguments.
  252. ;;;
  253. ;;; On the other hand, apply-to-args is a syntacticly convenient way to
  254. ;;; perform binding in many circumstances when the "let" family of
  255. ;;; of forms don't cut it.  E.g.:
  256. ;;;
  257. ;;;    (apply-to-args (return-3d-mouse-coords)
  258. ;;;      (lambda (x y z)
  259. ;;;        ...))
  260. ;;;
  261.  
  262. (define (apply-to-args args fn) (apply fn args))
  263.  
  264. (defmacro false-if-exception (expr)
  265.   `(catch #t (lambda () ,expr)
  266.       (lambda args #f)))
  267.  
  268.  
  269.  
  270. ;;; {General Properties}
  271. ;;;
  272.  
  273. ;; This is a more modern interface to properties.  It will replace all
  274. ;; other property-like things eventually.
  275.  
  276. (define (make-object-property)
  277.   (let ((prop (primitive-make-property #f)))
  278.     (make-procedure-with-setter
  279.      (lambda (obj) (primitive-property-ref prop obj))
  280.      (lambda (obj val) (primitive-property-set! prop obj val)))))
  281.  
  282.  
  283.  
  284. ;;; {Symbol Properties}
  285. ;;;
  286.  
  287. (define (symbol-property sym prop)
  288.   (let ((pair (assoc prop (symbol-pref sym))))
  289.     (and pair (cdr pair))))
  290.  
  291. (define (set-symbol-property! sym prop val)
  292.   (let ((pair (assoc prop (symbol-pref sym))))
  293.     (if pair
  294.     (set-cdr! pair val)
  295.     (symbol-pset! sym (acons prop val (symbol-pref sym))))))
  296.  
  297. (define (symbol-property-remove! sym prop)
  298.   (let ((pair (assoc prop (symbol-pref sym))))
  299.     (if pair
  300.     (symbol-pset! sym (delq! pair (symbol-pref sym))))))
  301.  
  302.  
  303.  
  304. ;;; {Arrays}
  305. ;;;
  306.  
  307. (define (array-shape a)
  308.   (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
  309.        (array-dimensions a)))
  310.  
  311.  
  312.  
  313. ;;; {Keywords}
  314. ;;;
  315.  
  316. (define (kw-arg-ref args kw)
  317.   (let ((rem (member kw args)))
  318.     (and rem (pair? (cdr rem)) (cadr rem))))
  319.  
  320.  
  321.  
  322. ;;; {Structs}
  323. ;;;
  324.  
  325. (define (struct-layout s)
  326.   (struct-ref (struct-vtable s) vtable-index-layout))
  327.  
  328.  
  329.  
  330. ;;; {Environments}
  331. ;;;
  332.  
  333. (define the-environment
  334.   (procedure->syntax
  335.    (lambda (x e)
  336.      e)))
  337.  
  338. (define the-root-environment (the-environment))
  339.  
  340. (define (environment-module env)
  341.   (let ((closure (and (pair? env) (car (last-pair env)))))
  342.     (and closure (procedure-property closure 'module))))
  343.  
  344.  
  345.  
  346. ;;; {Records}
  347. ;;;
  348.  
  349. ;; Printing records: by default, records are printed as
  350. ;;
  351. ;;   #<type-name field1: val1 field2: val2 ...>
  352. ;;
  353. ;; You can change that by giving a custom printing function to
  354. ;; MAKE-RECORD-TYPE (after the list of field symbols).  This function
  355. ;; will be called like
  356. ;;
  357. ;;   (<printer> object port)
  358. ;;
  359. ;; It should print OBJECT to PORT.
  360.  
  361. (define (inherit-print-state old-port new-port)
  362.   (if (get-print-state old-port)
  363.       (port-with-print-state new-port (get-print-state old-port))
  364.       new-port))
  365.  
  366. ;; 0: type-name, 1: fields
  367. (define record-type-vtable
  368.   (make-vtable-vtable "prpr" 0
  369.               (lambda (s p)
  370.             (cond ((eq? s record-type-vtable)
  371.                    (display "#<record-type-vtable>" p))
  372.                   (else
  373.                    (display "#<record-type " p)
  374.                    (display (record-type-name s) p)
  375.                    (display ">" p))))))
  376.  
  377. (define (record-type? obj)
  378.   (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
  379.  
  380. (define (make-record-type type-name fields . opt)
  381.   (let ((printer-fn (and (pair? opt) (car opt))))
  382.     (let ((struct (make-struct record-type-vtable 0
  383.                    (make-struct-layout
  384.                 (apply string-append
  385.                        (map (lambda (f) "pw") fields)))
  386.                    (or printer-fn
  387.                    (lambda (s p)
  388.                      (display "#<" p)
  389.                      (display type-name p)
  390.                      (let loop ((fields fields)
  391.                         (off 0))
  392.                        (cond
  393.                     ((not (null? fields))
  394.                      (display " " p)
  395.                      (display (car fields) p)
  396.                      (display ": " p)
  397.                      (display (struct-ref s off) p)
  398.                      (loop (cdr fields) (+ 1 off)))))
  399.                      (display ">" p)))
  400.                    type-name
  401.                    (copy-tree fields))))
  402.       ;; Temporary solution: Associate a name to the record type descriptor
  403.       ;; so that the object system can create a wrapper class for it.
  404.       (set-struct-vtable-name! struct (if (symbol? type-name)
  405.                       type-name
  406.                       (string->symbol type-name)))
  407.       struct)))
  408.  
  409. (define (record-type-name obj)
  410.   (if (record-type? obj)
  411.       (struct-ref obj vtable-offset-user)
  412.       (error 'not-a-record-type obj)))
  413.  
  414. (define (record-type-fields obj)
  415.   (if (record-type? obj)
  416.       (struct-ref obj (+ 1 vtable-offset-user))
  417.       (error 'not-a-record-type obj)))
  418.  
  419. (define (record-constructor rtd . opt)
  420.   (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
  421.     (local-eval `(lambda ,field-names
  422.            (make-struct ',rtd 0 ,@(map (lambda (f)
  423.                          (if (memq f field-names)
  424.                              f
  425.                              #f))
  426.                            (record-type-fields rtd))))
  427.         the-root-environment)))
  428.  
  429. (define (record-predicate rtd)
  430.   (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
  431.  
  432. (define (%record-type-error rtd obj)  ;; private helper
  433.   (or (eq? rtd (record-type-descriptor obj))
  434.       (scm-error 'wrong-type-arg "%record-type-check"
  435.          "Wrong type record (want `~S'): ~S"
  436.          (list (record-type-name rtd) obj)
  437.          #f)))
  438.  
  439. (define (record-accessor rtd field-name)
  440.   (let* ((pos (list-index (record-type-fields rtd) field-name)))
  441.     (if (not pos)
  442.     (error 'no-such-field field-name))
  443.     (local-eval `(lambda (obj)
  444.                    (if (eq? (struct-vtable obj) ,rtd)
  445.                        (struct-ref obj ,pos)
  446.                        (%record-type-error ,rtd obj)))
  447.         the-root-environment)))
  448.  
  449. (define (record-modifier rtd field-name)
  450.   (let* ((pos (list-index (record-type-fields rtd) field-name)))
  451.     (if (not pos)
  452.     (error 'no-such-field field-name))
  453.     (local-eval `(lambda (obj val)
  454.                    (if (eq? (struct-vtable obj) ,rtd)
  455.                        (struct-set! obj ,pos val)
  456.                        (%record-type-error ,rtd obj)))
  457.         the-root-environment)))
  458.  
  459.  
  460. (define (record? obj)
  461.   (and (struct? obj) (record-type? (struct-vtable obj))))
  462.  
  463. (define (record-type-descriptor obj)
  464.   (if (struct? obj)
  465.       (struct-vtable obj)
  466.       (error 'not-a-record obj)))
  467.  
  468. (provide 'record)
  469.  
  470.  
  471.  
  472. ;;; {Booleans}
  473. ;;;
  474.  
  475. (define (->bool x) (not (not x)))
  476.  
  477.  
  478.  
  479. ;;; {Symbols}
  480. ;;;
  481.  
  482. (define (symbol-append . args)
  483.   (string->symbol (apply string-append (map symbol->string args))))
  484.  
  485. (define (list->symbol . args)
  486.   (string->symbol (apply list->string args)))
  487.  
  488. (define (symbol . args)
  489.   (string->symbol (apply string args)))
  490.  
  491.  
  492.  
  493. ;;; {Lists}
  494. ;;;
  495.  
  496. (define (list-index l k)
  497.   (let loop ((n 0)
  498.          (l l))
  499.     (and (not (null? l))
  500.      (if (eq? (car l) k)
  501.          n
  502.          (loop (+ n 1) (cdr l))))))
  503.  
  504.  
  505.  
  506. ;;; {and-map and or-map}
  507. ;;;
  508. ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
  509. ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
  510. ;;;
  511.  
  512. ;; and-map f l
  513. ;;
  514. ;; Apply f to successive elements of l until exhaustion or f returns #f.
  515. ;; If returning early, return #f.  Otherwise, return the last value returned
  516. ;; by f.  If f has never been called because l is empty, return #t.
  517. ;;
  518. (define (and-map f lst)
  519.   (let loop ((result #t)
  520.          (l lst))
  521.     (and result
  522.      (or (and (null? l)
  523.           result)
  524.          (loop (f (car l)) (cdr l))))))
  525.  
  526. ;; or-map f l
  527. ;;
  528. ;; Apply f to successive elements of l until exhaustion or while f returns #f.
  529. ;; If returning early, return the return value of f.
  530. ;;
  531. (define (or-map f lst)
  532.   (let loop ((result #f)
  533.          (l lst))
  534.     (or result
  535.     (and (not (null? l))
  536.          (loop (f (car l)) (cdr l))))))
  537.  
  538.  
  539.  
  540. (if (provided? 'posix)
  541.     (primitive-load-path "ice-9/posix.scm"))
  542.  
  543. (if (provided? 'socket)
  544.     (primitive-load-path "ice-9/networking.scm"))
  545.  
  546. ;; For reference, Emacs file-exists-p uses stat in this same way.
  547. ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
  548. ;; C where all that's needed is to inspect the return from stat().
  549. (define file-exists?
  550.   (if (provided? 'posix)
  551.       (lambda (str)
  552.     (->bool (false-if-exception (stat str))))
  553.       (lambda (str)
  554.     (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
  555.                (lambda args #f))))
  556.       (if port (begin (close-port port) #t)
  557.           #f)))))
  558.  
  559. (define file-is-directory?
  560.   (if (provided? 'posix)
  561.       (lambda (str)
  562.     (eq? (stat:type (stat str)) 'directory))
  563.       (lambda (str)
  564.     (let ((port (catch 'system-error
  565.                (lambda () (open-file (string-append str "/.")
  566.                          OPEN_READ))
  567.                (lambda args #f))))
  568.       (if port (begin (close-port port) #t)
  569.           #f)))))
  570.  
  571. (define (has-suffix? str suffix)
  572.   (let ((sufl (string-length suffix))
  573.     (sl (string-length str)))
  574.     (and (> sl sufl)
  575.      (string=? (substring str (- sl sufl) sl) suffix))))
  576.  
  577. (define (system-error-errno args)
  578.   (if (eq? (car args) 'system-error)
  579.       (car (list-ref args 4))
  580.       #f))
  581.  
  582.  
  583.  
  584. ;;; {Error Handling}
  585. ;;;
  586.  
  587. (define (error . args)
  588.   (save-stack)
  589.   (if (null? args)
  590.       (scm-error 'misc-error #f "?" #f #f)
  591.       (let loop ((msg "~A")
  592.          (rest (cdr args)))
  593.     (if (not (null? rest))
  594.         (loop (string-append msg " ~S")
  595.           (cdr rest))
  596.         (scm-error 'misc-error #f msg args #f)))))
  597.  
  598. ;; bad-throw is the hook that is called upon a throw to a an unhandled
  599. ;; key (unless the throw has four arguments, in which case
  600. ;; it's usually interpreted as an error throw.)
  601. ;; If the key has a default handler (a throw-handler-default property),
  602. ;; it is applied to the throw.
  603. ;;
  604. (define (bad-throw key . args)
  605.   (let ((default (symbol-property key 'throw-handler-default)))
  606.     (or (and default (apply default key args))
  607.     (apply error "unhandled-exception:" key args))))
  608.  
  609.  
  610.  
  611. (define (tm:sec obj) (vector-ref obj 0))
  612. (define (tm:min obj) (vector-ref obj 1))
  613. (define (tm:hour obj) (vector-ref obj 2))
  614. (define (tm:mday obj) (vector-ref obj 3))
  615. (define (tm:mon obj) (vector-ref obj 4))
  616. (define (tm:year obj) (vector-ref obj 5))
  617. (define (tm:wday obj) (vector-ref obj 6))
  618. (define (tm:yday obj) (vector-ref obj 7))
  619. (define (tm:isdst obj) (vector-ref obj 8))
  620. (define (tm:gmtoff obj) (vector-ref obj 9))
  621. (define (tm:zone obj) (vector-ref obj 10))
  622.  
  623. (define (set-tm:sec obj val) (vector-set! obj 0 val))
  624. (define (set-tm:min obj val) (vector-set! obj 1 val))
  625. (define (set-tm:hour obj val) (vector-set! obj 2 val))
  626. (define (set-tm:mday obj val) (vector-set! obj 3 val))
  627. (define (set-tm:mon obj val) (vector-set! obj 4 val))
  628. (define (set-tm:year obj val) (vector-set! obj 5 val))
  629. (define (set-tm:wday obj val) (vector-set! obj 6 val))
  630. (define (set-tm:yday obj val) (vector-set! obj 7 val))
  631. (define (set-tm:isdst obj val) (vector-set! obj 8 val))
  632. (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
  633. (define (set-tm:zone obj val) (vector-set! obj 10 val))
  634.  
  635. (define (tms:clock obj) (vector-ref obj 0))
  636. (define (tms:utime obj) (vector-ref obj 1))
  637. (define (tms:stime obj) (vector-ref obj 2))
  638. (define (tms:cutime obj) (vector-ref obj 3))
  639. (define (tms:cstime obj) (vector-ref obj 4))
  640.  
  641. (define file-position ftell)
  642. (define (file-set-position port offset . whence)
  643.   (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
  644.     (seek port offset whence)))
  645.  
  646. (define (move->fdes fd/port fd)
  647.   (cond ((integer? fd/port)
  648.      (dup->fdes fd/port fd)
  649.      (close fd/port)
  650.      fd)
  651.     (else
  652.      (primitive-move->fdes fd/port fd)
  653.      (set-port-revealed! fd/port 1)
  654.      fd/port)))
  655.  
  656. (define (release-port-handle port)
  657.   (let ((revealed (port-revealed port)))
  658.     (if (> revealed 0)
  659.     (set-port-revealed! port (- revealed 1)))))
  660.  
  661. (define (dup->port port/fd mode . maybe-fd)
  662.   (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
  663.               mode)))
  664.     (if (pair? maybe-fd)
  665.     (set-port-revealed! port 1))
  666.     port))
  667.  
  668. (define (dup->inport port/fd . maybe-fd)
  669.   (apply dup->port port/fd "r" maybe-fd))
  670.  
  671. (define (dup->outport port/fd . maybe-fd)
  672.   (apply dup->port port/fd "w" maybe-fd))
  673.  
  674. (define (dup port/fd . maybe-fd)
  675.   (if (integer? port/fd)
  676.       (apply dup->fdes port/fd maybe-fd)
  677.       (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
  678.  
  679. (define (duplicate-port port modes)
  680.   (dup->port port modes))
  681.  
  682. (define (fdes->inport fdes)
  683.   (let loop ((rest-ports (fdes->ports fdes)))
  684.     (cond ((null? rest-ports)
  685.        (let ((result (fdopen fdes "r")))
  686.          (set-port-revealed! result 1)
  687.          result))
  688.       ((input-port? (car rest-ports))
  689.        (set-port-revealed! (car rest-ports)
  690.                    (+ (port-revealed (car rest-ports)) 1))
  691.        (car rest-ports))
  692.       (else
  693.        (loop (cdr rest-ports))))))
  694.  
  695. (define (fdes->outport fdes)
  696.   (let loop ((rest-ports (fdes->ports fdes)))
  697.     (cond ((null? rest-ports)
  698.        (let ((result (fdopen fdes "w")))
  699.          (set-port-revealed! result 1)
  700.          result))
  701.       ((output-port? (car rest-ports))
  702.        (set-port-revealed! (car rest-ports)
  703.                    (+ (port-revealed (car rest-ports)) 1))
  704.        (car rest-ports))
  705.       (else
  706.        (loop (cdr rest-ports))))))
  707.  
  708. (define (port->fdes port)
  709.   (set-port-revealed! port (+ (port-revealed port) 1))
  710.   (fileno port))
  711.  
  712. (define (setenv name value)
  713.   (if value
  714.       (putenv (string-append name "=" value))
  715.       (putenv name)))
  716.  
  717. (define (unsetenv name)
  718.   "Remove the entry for NAME from the environment."
  719.   (putenv name))
  720.  
  721.  
  722.  
  723. ;;; {Load Paths}
  724. ;;;
  725.  
  726. ;;; Here for backward compatability
  727. ;;
  728. (define scheme-file-suffix (lambda () ".scm"))
  729.  
  730. (define (in-vicinity vicinity file)
  731.   (let ((tail (let ((len (string-length vicinity)))
  732.         (if (zero? len)
  733.             #f
  734.             (string-ref vicinity (- len 1))))))
  735.     (string-append vicinity
  736.            (if (or (not tail)
  737.                (eq? tail #\/))
  738.                ""
  739.                "/")
  740.            file)))
  741.  
  742.  
  743.  
  744. ;;; {Help for scm_shell}
  745. ;;;
  746. ;;; The argument-processing code used by Guile-based shells generates
  747. ;;; Scheme code based on the argument list.  This page contains help
  748. ;;; functions for the code it generates.
  749. ;;;
  750.  
  751. (define (command-line) (program-arguments))
  752.  
  753. ;; This is mostly for the internal use of the code generated by
  754. ;; scm_compile_shell_switches.
  755.  
  756. (define (turn-on-debugging)
  757.   (debug-enable 'debug)
  758.   (debug-enable 'backtrace)
  759.   (read-enable 'positions))
  760.  
  761. (define (load-user-init)
  762.   (let* ((home (or (getenv "HOME")
  763.            (false-if-exception (passwd:dir (getpwuid (getuid))))
  764.            "/"))  ;; fallback for cygwin etc.
  765.      (init-file (in-vicinity home ".guile")))
  766.     (if (file-exists? init-file)
  767.     (primitive-load init-file))))
  768.  
  769.  
  770.  
  771. ;;; {Loading by paths}
  772. ;;;
  773.  
  774. ;;; Load a Scheme source file named NAME, searching for it in the
  775. ;;; directories listed in %load-path, and applying each of the file
  776. ;;; name extensions listed in %load-extensions.
  777. (define (load-from-path name)
  778.   (start-stack 'load-stack
  779.            (primitive-load-path name)))
  780.  
  781.  
  782.  
  783.  
  784. ;;; {Transcendental Functions}
  785. ;;;
  786. ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
  787. ;;; Written by Jerry D. Hedden, (C) FSF.
  788. ;;; See the file `COPYING' for terms applying to this program.
  789. ;;;
  790.  
  791. (define expt
  792.   (let ((integer-expt integer-expt))
  793.     (lambda (z1 z2)
  794.       (cond ((and (exact? z2) (integer? z2))
  795.          (integer-expt z1 z2))
  796.         ((and (real? z2) (real? z1) (>= z1 0))
  797.          ($expt z1 z2))
  798.         (else
  799.          (exp (* z2 (log z1))))))))
  800.  
  801. (define (sinh z)
  802.   (if (real? z) ($sinh z)
  803.       (let ((x (real-part z)) (y (imag-part z)))
  804.     (make-rectangular (* ($sinh x) ($cos y))
  805.               (* ($cosh x) ($sin y))))))
  806. (define (cosh z)
  807.   (if (real? z) ($cosh z)
  808.       (let ((x (real-part z)) (y (imag-part z)))
  809.     (make-rectangular (* ($cosh x) ($cos y))
  810.               (* ($sinh x) ($sin y))))))
  811. (define (tanh z)
  812.   (if (real? z) ($tanh z)
  813.       (let* ((x (* 2 (real-part z)))
  814.          (y (* 2 (imag-part z)))
  815.          (w (+ ($cosh x) ($cos y))))
  816.     (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
  817.  
  818. (define (asinh z)
  819.   (if (real? z) ($asinh z)
  820.       (log (+ z (sqrt (+ (* z z) 1))))))
  821.  
  822. (define (acosh z)
  823.   (if (and (real? z) (>= z 1))
  824.       ($acosh z)
  825.       (log (+ z (sqrt (- (* z z) 1))))))
  826.  
  827. (define (atanh z)
  828.   (if (and (real? z) (> z -1) (< z 1))
  829.       ($atanh z)
  830.       (/ (log (/ (+ 1 z) (- 1 z))) 2)))
  831.  
  832. (define (sin z)
  833.   (if (real? z) ($sin z)
  834.       (let ((x (real-part z)) (y (imag-part z)))
  835.     (make-rectangular (* ($sin x) ($cosh y))
  836.               (* ($cos x) ($sinh y))))))
  837. (define (cos z)
  838.   (if (real? z) ($cos z)
  839.       (let ((x (real-part z)) (y (imag-part z)))
  840.     (make-rectangular (* ($cos x) ($cosh y))
  841.               (- (* ($sin x) ($sinh y)))))))
  842. (define (tan z)
  843.   (if (real? z) ($tan z)
  844.       (let* ((x (* 2 (real-part z)))
  845.          (y (* 2 (imag-part z)))
  846.          (w (+ ($cos x) ($cosh y))))
  847.     (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
  848.  
  849. (define (asin z)
  850.   (if (and (real? z) (>= z -1) (<= z 1))
  851.       ($asin z)
  852.       (* -i (asinh (* +i z)))))
  853.  
  854. (define (acos z)
  855.   (if (and (real? z) (>= z -1) (<= z 1))
  856.       ($acos z)
  857.       (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
  858.  
  859. (define (atan z . y)
  860.   (if (null? y)
  861.       (if (real? z) ($atan z)
  862.       (/ (log (/ (- +i z) (+ +i z))) +2i))
  863.       ($atan2 z (car y))))
  864.  
  865.  
  866.  
  867. ;;; {Reader Extensions}
  868. ;;;
  869. ;;; Reader code for various "#c" forms.
  870. ;;;
  871.  
  872. (read-hash-extend #\' (lambda (c port)
  873.             (read port)))
  874.  
  875. (define read-eval? (make-fluid))
  876. (fluid-set! read-eval? #f)
  877. (read-hash-extend #\.
  878.                   (lambda (c port)
  879.                     (if (fluid-ref read-eval?)
  880.                         (eval (read port) (interaction-environment))
  881.                         (error
  882.                          "#. read expansion found and read-eval? is #f."))))
  883.  
  884.  
  885.  
  886. ;;; {Command Line Options}
  887. ;;;
  888.  
  889. (define (get-option argv kw-opts kw-args return)
  890.   (cond
  891.    ((null? argv)
  892.     (return #f #f argv))
  893.  
  894.    ((or (not (eq? #\- (string-ref (car argv) 0)))
  895.     (eq? (string-length (car argv)) 1))
  896.     (return 'normal-arg (car argv) (cdr argv)))
  897.  
  898.    ((eq? #\- (string-ref (car argv) 1))
  899.     (let* ((kw-arg-pos (or (string-index (car argv) #\=)
  900.                (string-length (car argv))))
  901.        (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
  902.        (kw-opt? (member kw kw-opts))
  903.        (kw-arg? (member kw kw-args))
  904.        (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
  905.              (substring (car argv)
  906.                     (+ kw-arg-pos 1)
  907.                     (string-length (car argv))))
  908.             (and kw-arg?
  909.              (begin (set! argv (cdr argv)) (car argv))))))
  910.       (if (or kw-opt? kw-arg?)
  911.       (return kw arg (cdr argv))
  912.       (return 'usage-error kw (cdr argv)))))
  913.  
  914.    (else
  915.     (let* ((char (substring (car argv) 1 2))
  916.        (kw (symbol->keyword char)))
  917.       (cond
  918.  
  919.        ((member kw kw-opts)
  920.     (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
  921.            (new-argv (if (= 0 (string-length rest-car))
  922.                  (cdr argv)
  923.                  (cons (string-append "-" rest-car) (cdr argv)))))
  924.       (return kw #f new-argv)))
  925.  
  926.        ((member kw kw-args)
  927.     (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
  928.            (arg (if (= 0 (string-length rest-car))
  929.             (cadr argv)
  930.             rest-car))
  931.            (new-argv (if (= 0 (string-length rest-car))
  932.                  (cddr argv)
  933.                  (cdr argv))))
  934.       (return kw arg new-argv)))
  935.  
  936.        (else (return 'usage-error kw argv)))))))
  937.  
  938. (define (for-next-option proc argv kw-opts kw-args)
  939.   (let loop ((argv argv))
  940.     (get-option argv kw-opts kw-args
  941.         (lambda (opt opt-arg argv)
  942.           (and opt (proc opt opt-arg argv loop))))))
  943.  
  944. (define (display-usage-report kw-desc)
  945.   (for-each
  946.    (lambda (kw)
  947.      (or (eq? (car kw) #t)
  948.      (eq? (car kw) 'else)
  949.      (let* ((opt-desc kw)
  950.         (help (cadr opt-desc))
  951.         (opts (car opt-desc))
  952.         (opts-proper (if (string? (car opts)) (cdr opts) opts))
  953.         (arg-name (if (string? (car opts))
  954.                   (string-append "<" (car opts) ">")
  955.                   ""))
  956.         (left-part (string-append
  957.                 (with-output-to-string
  958.                   (lambda ()
  959.                 (map (lambda (x) (display (keyword->symbol x)) (display " "))
  960.                      opts-proper)))
  961.                 arg-name))
  962.         (middle-part (if (and (< (string-length left-part) 30)
  963.                       (< (string-length help) 40))
  964.                  (make-string (- 30 (string-length left-part)) #\ )
  965.                  "\n\t")))
  966.        (display left-part)
  967.        (display middle-part)
  968.        (display help)
  969.        (newline))))
  970.    kw-desc))
  971.  
  972.  
  973.  
  974. (define (transform-usage-lambda cases)
  975.   (let* ((raw-usage (delq! 'else (map car cases)))
  976.      (usage-sans-specials (map (lambda (x)
  977.                     (or (and (not (list? x)) x)
  978.                     (and (symbol? (car x)) #t)
  979.                     (and (boolean? (car x)) #t)
  980.                     x))
  981.                   raw-usage))
  982.      (usage-desc (delq! #t usage-sans-specials))
  983.      (kw-desc (map car usage-desc))
  984.      (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
  985.      (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
  986.      (transmogrified-cases (map (lambda (case)
  987.                       (cons (let ((opts (car case)))
  988.                           (if (or (boolean? opts) (eq? 'else opts))
  989.                           opts
  990.                           (cond
  991.                            ((symbol? (car opts))  opts)
  992.                            ((boolean? (car opts)) opts)
  993.                            ((string? (caar opts)) (cdar opts))
  994.                            (else (car opts)))))
  995.                         (cdr case)))
  996.                     cases)))
  997.     `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
  998.        (lambda (%argv)
  999.      (let %next-arg ((%argv %argv))
  1000.        (get-option %argv
  1001.                ',kw-opts
  1002.                ',kw-args
  1003.                (lambda (%opt %arg %new-argv)
  1004.              (case %opt
  1005.                ,@ transmogrified-cases))))))))
  1006.  
  1007.  
  1008.  
  1009.  
  1010. ;;; {Low Level Modules}
  1011. ;;;
  1012. ;;; These are the low level data structures for modules.
  1013. ;;;
  1014. ;;; Every module object is of the type 'module-type', which is a record
  1015. ;;; consisting of the following members:
  1016. ;;;
  1017. ;;; - eval-closure: the function that defines for its module the strategy that
  1018. ;;;   shall be followed when looking up symbols in the module.
  1019. ;;;
  1020. ;;;   An eval-closure is a function taking two arguments: the symbol to be
  1021. ;;;   looked up and a boolean value telling whether a binding for the symbol
  1022. ;;;   should be created if it does not exist yet.  If the symbol lookup
  1023. ;;;   succeeded (either because an existing binding was found or because a new
  1024. ;;;   binding was created), a variable object representing the binding is
  1025. ;;;   returned.  Otherwise, the value #f is returned.  Note that the eval
  1026. ;;;   closure does not take the module to be searched as an argument: During
  1027. ;;;   construction of the eval-closure, the eval-closure has to store the
  1028. ;;;   module it belongs to in its environment.  This means, that any
  1029. ;;;   eval-closure can belong to only one module.
  1030. ;;;
  1031. ;;;   The eval-closure of a module can be defined arbitrarily.  However, three
  1032. ;;;   special cases of eval-closures are to be distinguished: During startup
  1033. ;;;   the module system is not yet activated.  In this phase, no modules are
  1034. ;;;   defined and all bindings are automatically stored by the system in the
  1035. ;;;   pre-modules-obarray.  Since no eval-closures exist at this time, the
  1036. ;;;   functions which require an eval-closure as their argument need to be
  1037. ;;;   passed the value #f.
  1038. ;;;
  1039. ;;;   The other two special cases of eval-closures are the
  1040. ;;;   standard-eval-closure and the standard-interface-eval-closure.  Both
  1041. ;;;   behave equally for the case that no new binding is to be created.  The
  1042. ;;;   difference between the two comes in, when the boolean argument to the
  1043. ;;;   eval-closure indicates that a new binding shall be created if it is not
  1044. ;;;   found.
  1045. ;;;
  1046. ;;;   Given that no new binding shall be created, both standard eval-closures
  1047. ;;;   define the following standard strategy of searching bindings in the
  1048. ;;;   module: First, the module's obarray is searched for the symbol.  Second,
  1049. ;;;   if no binding for the symbol was found in the module's obarray, the
  1050. ;;;   module's binder procedure is exececuted.  If this procedure did not
  1051. ;;;   return a binding for the symbol, the modules referenced in the module's
  1052. ;;;   uses list are recursively searched for a binding of the symbol.  If the
  1053. ;;;   binding can not be found in these modules also, the symbol lookup has
  1054. ;;;   failed.
  1055. ;;;
  1056. ;;;   If a new binding shall be created, the standard-interface-eval-closure
  1057. ;;;   immediately returns indicating failure.  That is, it does not even try
  1058. ;;;   to look up the symbol.  In contrast, the standard-eval-closure would
  1059. ;;;   first search the obarray, and if no binding was found there, would
  1060. ;;;   create a new binding in the obarray, therefore not calling the binder
  1061. ;;;   procedure or searching the modules in the uses list.
  1062. ;;;
  1063. ;;;   The explanation of the following members obarray, binder and uses
  1064. ;;;   assumes that the symbol lookup follows the strategy that is defined in
  1065. ;;;   the standard-eval-closure and the standard-interface-eval-closure.
  1066. ;;;
  1067. ;;; - obarray: a hash table that maps symbols to variable objects.  In this
  1068. ;;;   hash table, the definitions are found that are local to the module (that
  1069. ;;;   is, not imported from other modules).  When looking up bindings in the
  1070. ;;;   module, this hash table is searched first.
  1071. ;;;
  1072. ;;; - binder: either #f or a function taking a module and a symbol argument.
  1073. ;;;   If it is a function it is called after the obarray has been
  1074. ;;;   unsuccessfully searched for a binding.  It then can provide bindings
  1075. ;;;   that would otherwise not be found locally in the module.
  1076. ;;;
  1077. ;;; - uses: a list of modules from which non-local bindings can be inherited.
  1078. ;;;   These modules are the third place queried for bindings after the obarray
  1079. ;;;   has been unsuccessfully searched and the binder function did not deliver
  1080. ;;;   a result either.
  1081. ;;;
  1082. ;;; - transformer: either #f or a function taking a scheme expression as
  1083. ;;;   delivered by read.  If it is a function, it will be called to perform
  1084. ;;;   syntax transformations (e. g. makro expansion) on the given scheme
  1085. ;;;   expression. The output of the transformer function will then be passed
  1086. ;;;   to Guile's internal memoizer.  This means that the output must be valid
  1087. ;;;   scheme code.  The only exception is, that the output may make use of the
  1088. ;;;   syntax extensions provided to identify the modules that a binding
  1089. ;;;   belongs to.
  1090. ;;;
  1091. ;;; - name: the name of the module.  This is used for all kinds of printing
  1092. ;;;   outputs.  In certain places the module name also serves as a way of
  1093. ;;;   identification.  When adding a module to the uses list of another
  1094. ;;;   module, it is made sure that the new uses list will not contain two
  1095. ;;;   modules of the same name.
  1096. ;;;
  1097. ;;; - kind: classification of the kind of module.  The value is (currently?)
  1098. ;;;   only used for printing.  It has no influence on how a module is treated.
  1099. ;;;   Currently the following values are used when setting the module kind:
  1100. ;;;   'module, 'directory, 'interface, 'custom-interface.  If no explicit kind
  1101. ;;;   is set, it defaults to 'module.
  1102. ;;;
  1103. ;;; - duplicates-handlers
  1104. ;;;
  1105. ;;; - duplicates-interface
  1106. ;;;
  1107. ;;; - observers
  1108. ;;;
  1109. ;;; - weak-observers
  1110. ;;;
  1111. ;;; - observer-id
  1112. ;;;
  1113. ;;; In addition, the module may (must?) contain a binding for
  1114. ;;; %module-public-interface... More explanations here...
  1115. ;;;
  1116. ;;; !!! warning: The interface to lazy binder procedures is going
  1117. ;;; to be changed in an incompatible way to permit all the basic
  1118. ;;; module ops to be virtualized.
  1119. ;;;
  1120. ;;; (make-module size use-list lazy-binding-proc) => module
  1121. ;;; module-{obarray,uses,binder}[|-set!]
  1122. ;;; (module? obj) => [#t|#f]
  1123. ;;; (module-locally-bound? module symbol) => [#t|#f]
  1124. ;;; (module-bound? module symbol) => [#t|#f]
  1125. ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
  1126. ;;; (module-symbol-interned? module symbol) => [#t|#f]
  1127. ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
  1128. ;;; (module-variable module symbol) => [#<variable ...> | #f]
  1129. ;;; (module-symbol-binding module symbol opt-value)
  1130. ;;;        => [ <obj> | opt-value | an error occurs ]
  1131. ;;; (module-make-local-var! module symbol) => #<variable...>
  1132. ;;; (module-add! module symbol var) => unspecified
  1133. ;;; (module-remove! module symbol) =>  unspecified
  1134. ;;; (module-for-each proc module) => unspecified
  1135. ;;; (make-scm-module) => module ; a lazy copy of the symhash module
  1136. ;;; (set-current-module module) => unspecified
  1137. ;;; (current-module) => #<module...>
  1138. ;;;
  1139. ;;;
  1140.  
  1141.  
  1142.  
  1143. ;;; {Printing Modules}
  1144. ;;;
  1145.  
  1146. ;; This is how modules are printed.  You can re-define it.
  1147. ;; (Redefining is actually more complicated than simply redefining
  1148. ;; %print-module because that would only change the binding and not
  1149. ;; the value stored in the vtable that determines how record are
  1150. ;; printed. Sigh.)
  1151.  
  1152. (define (%print-module mod port)  ; unused args: depth length style table)
  1153.   (display "#<" port)
  1154.   (display (or (module-kind mod) "module") port)
  1155.   (let ((name (module-name mod)))
  1156.     (if name
  1157.     (begin
  1158.       (display " " port)
  1159.       (display name port))))
  1160.   (display " " port)
  1161.   (display (number->string (object-address mod) 16) port)
  1162.   (display ">" port))
  1163.  
  1164. ;; module-type
  1165. ;;
  1166. ;; A module is characterized by an obarray in which local symbols
  1167. ;; are interned, a list of modules, "uses", from which non-local
  1168. ;; bindings can be inherited, and an optional lazy-binder which
  1169. ;; is a (CLOSURE module symbol) which, as a last resort, can provide
  1170. ;; bindings that would otherwise not be found locally in the module.
  1171. ;;
  1172. ;; NOTE: If you change anything here, you also need to change
  1173. ;; libguile/modules.h.
  1174. ;;
  1175. (define module-type
  1176.   (make-record-type 'module
  1177.             '(obarray uses binder eval-closure transformer name kind
  1178.               duplicates-handlers duplicates-interface
  1179.               observers weak-observers observer-id)
  1180.             %print-module))
  1181.  
  1182. ;; make-module &opt size uses binder
  1183. ;;
  1184. ;; Create a new module, perhaps with a particular size of obarray,
  1185. ;; initial uses list, or binding procedure.
  1186. ;;
  1187. (define make-module
  1188.     (lambda args
  1189.  
  1190.       (define (parse-arg index default)
  1191.     (if (> (length args) index)
  1192.         (list-ref args index)
  1193.         default))
  1194.  
  1195.       (if (> (length args) 3)
  1196.       (error "Too many args to make-module." args))
  1197.  
  1198.       (let ((size (parse-arg 0 31))
  1199.         (uses (parse-arg 1 '()))
  1200.         (binder (parse-arg 2 #f)))
  1201.  
  1202.     (if (not (integer? size))
  1203.         (error "Illegal size to make-module." size))
  1204.     (if (not (and (list? uses)
  1205.               (and-map module? uses)))
  1206.         (error "Incorrect use list." uses))
  1207.     (if (and binder (not (procedure? binder)))
  1208.         (error
  1209.          "Lazy-binder expected to be a procedure or #f." binder))
  1210.  
  1211.     (let ((module (module-constructor (make-hash-table size)
  1212.                       uses binder #f #f #f #f #f #f
  1213.                       '()
  1214.                       (make-weak-value-hash-table 31)
  1215.                       0)))
  1216.  
  1217.       ;; We can't pass this as an argument to module-constructor,
  1218.       ;; because we need it to close over a pointer to the module
  1219.       ;; itself.
  1220.       (set-module-eval-closure! module (standard-eval-closure module))
  1221.  
  1222.       module))))
  1223.  
  1224. (define module-constructor (record-constructor module-type))
  1225. (define module-obarray  (record-accessor module-type 'obarray))
  1226. (define set-module-obarray! (record-modifier module-type 'obarray))
  1227. (define module-uses  (record-accessor module-type 'uses))
  1228. (define set-module-uses! (record-modifier module-type 'uses))
  1229. (define module-binder (record-accessor module-type 'binder))
  1230. (define set-module-binder! (record-modifier module-type 'binder))
  1231.  
  1232. ;; NOTE: This binding is used in libguile/modules.c.
  1233. (define module-eval-closure (record-accessor module-type 'eval-closure))
  1234.  
  1235. (define module-transformer (record-accessor module-type 'transformer))
  1236. (define set-module-transformer! (record-modifier module-type 'transformer))
  1237. (define module-name (record-accessor module-type 'name))
  1238. (define set-module-name! (record-modifier module-type 'name))
  1239. (define module-kind (record-accessor module-type 'kind))
  1240. (define set-module-kind! (record-modifier module-type 'kind))
  1241. (define module-duplicates-handlers
  1242.   (record-accessor module-type 'duplicates-handlers))
  1243. (define set-module-duplicates-handlers!
  1244.   (record-modifier module-type 'duplicates-handlers))
  1245. (define module-duplicates-interface
  1246.   (record-accessor module-type 'duplicates-interface))
  1247. (define set-module-duplicates-interface!
  1248.   (record-modifier module-type 'duplicates-interface))
  1249. (define module-observers (record-accessor module-type 'observers))
  1250. (define set-module-observers! (record-modifier module-type 'observers))
  1251. (define module-weak-observers (record-accessor module-type 'weak-observers))
  1252. (define module-observer-id (record-accessor module-type 'observer-id))
  1253. (define set-module-observer-id! (record-modifier module-type 'observer-id))
  1254. (define module? (record-predicate module-type))
  1255.  
  1256. (define set-module-eval-closure!
  1257.   (let ((setter (record-modifier module-type 'eval-closure)))
  1258.     (lambda (module closure)
  1259.       (setter module closure)
  1260.       ;; Make it possible to lookup the module from the environment.
  1261.       ;; This implementation is correct since an eval closure can belong
  1262.       ;; to maximally one module.
  1263.       (set-procedure-property! closure 'module module))))
  1264.  
  1265.  
  1266.  
  1267. ;;; {Observer protocol}
  1268. ;;;
  1269.  
  1270. (define (module-observe module proc)
  1271.   (set-module-observers! module (cons proc (module-observers module)))
  1272.   (cons module proc))
  1273.  
  1274. (define (module-observe-weak module proc)
  1275.   (let ((id (module-observer-id module)))
  1276.     (hash-set! (module-weak-observers module) id proc)
  1277.     (set-module-observer-id! module (+ 1 id))
  1278.     (cons module id)))
  1279.  
  1280. (define (module-unobserve token)
  1281.   (let ((module (car token))
  1282.     (id (cdr token)))
  1283.     (if (integer? id)
  1284.     (hash-remove! (module-weak-observers module) id)
  1285.     (set-module-observers! module (delq1! id (module-observers module)))))
  1286.   *unspecified*)
  1287.  
  1288. (define module-defer-observers #f)
  1289. (define module-defer-observers-mutex (make-mutex))
  1290. (define module-defer-observers-table (make-hash-table))
  1291.  
  1292. (define (module-modified m)
  1293.   (if module-defer-observers
  1294.       (hash-set! module-defer-observers-table m #t)
  1295.       (module-call-observers m)))
  1296.  
  1297. ;;; This function can be used to delay calls to observers so that they
  1298. ;;; can be called once only in the face of massive updating of modules.
  1299. ;;;
  1300. (define (call-with-deferred-observers thunk)
  1301.   (dynamic-wind
  1302.       (lambda ()
  1303.     (lock-mutex module-defer-observers-mutex)
  1304.     (set! module-defer-observers #t))
  1305.       thunk
  1306.       (lambda ()
  1307.     (set! module-defer-observers #f)
  1308.     (hash-for-each (lambda (m dummy)
  1309.              (module-call-observers m))
  1310.                module-defer-observers-table)
  1311.     (hash-clear! module-defer-observers-table)
  1312.     (unlock-mutex module-defer-observers-mutex))))
  1313.  
  1314. (define (module-call-observers m)
  1315.   (for-each (lambda (proc) (proc m)) (module-observers m))
  1316.   (hash-fold (lambda (id proc res) (proc m)) #f (module-weak-observers m)))
  1317.  
  1318.  
  1319.  
  1320. ;;; {Module Searching in General}
  1321. ;;;
  1322. ;;; We sometimes want to look for properties of a symbol
  1323. ;;; just within the obarray of one module.  If the property
  1324. ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
  1325. ;;; DISPLAY is locally rebound in the module `safe-guile'.''
  1326. ;;;
  1327. ;;;
  1328. ;;; Other times, we want to test for a symbol property in the obarray
  1329. ;;; of M and, if it is not found there, try each of the modules in the
  1330. ;;; uses list of M.  This is the normal way of testing for some
  1331. ;;; property, so we state these properties without qualification as
  1332. ;;; in: ``The symbol 'fnord is interned in module M because it is
  1333. ;;; interned locally in module M2 which is a member of the uses list
  1334. ;;; of M.''
  1335. ;;;
  1336.  
  1337. ;; module-search fn m
  1338. ;;
  1339. ;; return the first non-#f result of FN applied to M and then to
  1340. ;; the modules in the uses of m, and so on recursively.  If all applications
  1341. ;; return #f, then so does this function.
  1342. ;;
  1343. (define (module-search fn m v)
  1344.   (define (loop pos)
  1345.     (and (pair? pos)
  1346.      (or (module-search fn (car pos) v)
  1347.          (loop (cdr pos)))))
  1348.   (or (fn m v)
  1349.       (loop (module-uses m))))
  1350.  
  1351.  
  1352. ;;; {Is a symbol bound in a module?}
  1353. ;;;
  1354. ;;; Symbol S in Module M is bound if S is interned in M and if the binding
  1355. ;;; of S in M has been set to some well-defined value.
  1356. ;;;
  1357.  
  1358. ;; module-locally-bound? module symbol
  1359. ;;
  1360. ;; Is a symbol bound (interned and defined) locally in a given module?
  1361. ;;
  1362. (define (module-locally-bound? m v)
  1363.   (let ((var (module-local-variable m v)))
  1364.     (and var
  1365.      (variable-bound? var))))
  1366.  
  1367. ;; module-bound? module symbol
  1368. ;;
  1369. ;; Is a symbol bound (interned and defined) anywhere in a given module
  1370. ;; or its uses?
  1371. ;;
  1372. (define (module-bound? m v)
  1373.   (module-search module-locally-bound? m v))
  1374.  
  1375. ;;; {Is a symbol interned in a module?}
  1376. ;;;
  1377. ;;; Symbol S in Module M is interned if S occurs in
  1378. ;;; of S in M has been set to some well-defined value.
  1379. ;;;
  1380. ;;; It is possible to intern a symbol in a module without providing
  1381. ;;; an initial binding for the corresponding variable.  This is done
  1382. ;;; with:
  1383. ;;;       (module-add! module symbol (make-undefined-variable))
  1384. ;;;
  1385. ;;; In that case, the symbol is interned in the module, but not
  1386. ;;; bound there.  The unbound symbol shadows any binding for that
  1387. ;;; symbol that might otherwise be inherited from a member of the uses list.
  1388. ;;;
  1389.  
  1390. (define (module-obarray-get-handle ob key)
  1391.   ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
  1392.  
  1393. (define (module-obarray-ref ob key)
  1394.   ((if (symbol? key) hashq-ref hash-ref) ob key))
  1395.  
  1396. (define (module-obarray-set! ob key val)
  1397.   ((if (symbol? key) hashq-set! hash-set!) ob key val))
  1398.  
  1399. (define (module-obarray-remove! ob key)
  1400.   ((if (symbol? key) hashq-remove! hash-remove!) ob key))
  1401.  
  1402. ;; module-symbol-locally-interned? module symbol
  1403. ;;
  1404. ;; is a symbol interned (not neccessarily defined) locally in a given module
  1405. ;; or its uses?  Interned symbols shadow inherited bindings even if
  1406. ;; they are not themselves bound to a defined value.
  1407. ;;
  1408. (define (module-symbol-locally-interned? m v)
  1409.   (not (not (module-obarray-get-handle (module-obarray m) v))))
  1410.  
  1411. ;; module-symbol-interned? module symbol
  1412. ;;
  1413. ;; is a symbol interned (not neccessarily defined) anywhere in a given module
  1414. ;; or its uses?  Interned symbols shadow inherited bindings even if
  1415. ;; they are not themselves bound to a defined value.
  1416. ;;
  1417. (define (module-symbol-interned? m v)
  1418.   (module-search module-symbol-locally-interned? m v))
  1419.  
  1420.  
  1421. ;;; {Mapping modules x symbols --> variables}
  1422. ;;;
  1423.  
  1424. ;; module-local-variable module symbol
  1425. ;; return the local variable associated with a MODULE and SYMBOL.
  1426. ;;
  1427. ;;; This function is very important. It is the only function that can
  1428. ;;; return a variable from a module other than the mutators that store
  1429. ;;; new variables in modules.  Therefore, this function is the location
  1430. ;;; of the "lazy binder" hack.
  1431. ;;;
  1432. ;;; If symbol is defined in MODULE, and if the definition binds symbol
  1433. ;;; to a variable, return that variable object.
  1434. ;;;
  1435. ;;; If the symbols is not found at first, but the module has a lazy binder,
  1436. ;;; then try the binder.
  1437. ;;;
  1438. ;;; If the symbol is not found at all, return #f.
  1439. ;;;
  1440. (define (module-local-variable m v)
  1441. ;  (caddr
  1442. ;   (list m v
  1443.      (let ((b (module-obarray-ref (module-obarray m) v)))
  1444.        (or (and (variable? b) b)
  1445.            (and (module-binder m)
  1446.             ((module-binder m) m v #f)))))
  1447. ;))
  1448.  
  1449. ;; module-variable module symbol
  1450. ;;
  1451. ;; like module-local-variable, except search the uses in the
  1452. ;; case V is not found in M.
  1453. ;;
  1454. ;; NOTE: This function is superseded with C code (see modules.c)
  1455. ;;;      when using the standard eval closure.
  1456. ;;
  1457. (define (module-variable m v)
  1458.   (module-search module-local-variable m v))
  1459.  
  1460.  
  1461. ;;; {Mapping modules x symbols --> bindings}
  1462. ;;;
  1463. ;;; These are similar to the mapping to variables, except that the
  1464. ;;; variable is dereferenced.
  1465. ;;;
  1466.  
  1467. ;; module-symbol-binding module symbol opt-value
  1468. ;;
  1469. ;; return the binding of a variable specified by name within
  1470. ;; a given module, signalling an error if the variable is unbound.
  1471. ;; If the OPT-VALUE is passed, then instead of signalling an error,
  1472. ;; return OPT-VALUE.
  1473. ;;
  1474. (define (module-symbol-local-binding m v . opt-val)
  1475.   (let ((var (module-local-variable m v)))
  1476.     (if (and var (variable-bound? var))
  1477.     (variable-ref var)
  1478.     (if (not (null? opt-val))
  1479.         (car opt-val)
  1480.         (error "Locally unbound variable." v)))))
  1481.  
  1482. ;; module-symbol-binding module symbol opt-value
  1483. ;;
  1484. ;; return the binding of a variable specified by name within
  1485. ;; a given module, signalling an error if the variable is unbound.
  1486. ;; If the OPT-VALUE is passed, then instead of signalling an error,
  1487. ;; return OPT-VALUE.
  1488. ;;
  1489. (define (module-symbol-binding m v . opt-val)
  1490.   (let ((var (module-variable m v)))
  1491.     (if (and var (variable-bound? var))
  1492.     (variable-ref var)
  1493.     (if (not (null? opt-val))
  1494.         (car opt-val)
  1495.         (error "Unbound variable." v)))))
  1496.  
  1497.  
  1498.  
  1499.  
  1500. ;;; {Adding Variables to Modules}
  1501. ;;;
  1502.  
  1503. ;; module-make-local-var! module symbol
  1504. ;;
  1505. ;; ensure a variable for V in the local namespace of M.
  1506. ;; If no variable was already there, then create a new and uninitialzied
  1507. ;; variable.
  1508. ;;
  1509. ;; This function is used in modules.c.
  1510. ;;
  1511. (define (module-make-local-var! m v)
  1512.   (or (let ((b (module-obarray-ref (module-obarray m) v)))
  1513.     (and (variable? b)
  1514.          (begin
  1515.            ;; Mark as modified since this function is called when
  1516.            ;; the standard eval closure defines a binding
  1517.            (module-modified m)
  1518.            b)))
  1519.  
  1520.       ;; Create a new local variable.
  1521.       (let ((local-var (make-undefined-variable)))
  1522.         (module-add! m v local-var)
  1523.         local-var)))
  1524.  
  1525. ;; module-ensure-local-variable! module symbol
  1526. ;;
  1527. ;; Ensure that there is a local variable in MODULE for SYMBOL.  If
  1528. ;; there is no binding for SYMBOL, create a new uninitialized
  1529. ;; variable.  Return the local variable.
  1530. ;;
  1531. (define (module-ensure-local-variable! module symbol)
  1532.   (or (module-local-variable module symbol)
  1533.       (let ((var (make-undefined-variable)))
  1534.     (module-add! module symbol var)
  1535.     var)))
  1536.  
  1537. ;; module-add! module symbol var
  1538. ;;
  1539. ;; ensure a particular variable for V in the local namespace of M.
  1540. ;;
  1541. (define (module-add! m v var)
  1542.   (if (not (variable? var))
  1543.       (error "Bad variable to module-add!" var))
  1544.   (module-obarray-set! (module-obarray m) v var)
  1545.   (module-modified m))
  1546.  
  1547. ;; module-remove!
  1548. ;;
  1549. ;; make sure that a symbol is undefined in the local namespace of M.
  1550. ;;
  1551. (define (module-remove! m v)
  1552.   (module-obarray-remove! (module-obarray m) v)
  1553.   (module-modified m))
  1554.  
  1555. (define (module-clear! m)
  1556.   (hash-clear! (module-obarray m))
  1557.   (module-modified m))
  1558.  
  1559. ;; MODULE-FOR-EACH -- exported
  1560. ;;
  1561. ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
  1562. ;;
  1563. (define (module-for-each proc module)
  1564.   (hash-for-each proc (module-obarray module)))
  1565.  
  1566. (define (module-map proc module)
  1567.   (hash-map->list proc (module-obarray module)))
  1568.  
  1569.  
  1570.  
  1571. ;;; {Low Level Bootstrapping}
  1572. ;;;
  1573.  
  1574. ;; make-root-module
  1575.  
  1576. ;; A root module uses the pre-modules-obarray as its obarray.  This
  1577. ;; special obarray accumulates all bindings that have been established
  1578. ;; before the module system is fully booted.
  1579. ;;
  1580. ;; (The obarray continues to be used by code that has been closed over
  1581. ;;  before the module system has been booted.)
  1582.  
  1583. (define (make-root-module)
  1584.   (let ((m (make-module 0)))
  1585.     (set-module-obarray! m (%get-pre-modules-obarray))
  1586.     m))
  1587.  
  1588. ;; make-scm-module
  1589.  
  1590. ;; The root interface is a module that uses the same obarray as the
  1591. ;; root module.  It does not allow new definitions, tho.
  1592.  
  1593. (define (make-scm-module)
  1594.   (let ((m (make-module 0)))
  1595.     (set-module-obarray! m (%get-pre-modules-obarray))
  1596.     (set-module-eval-closure! m (standard-interface-eval-closure m))
  1597.     m))
  1598.  
  1599.  
  1600.  
  1601.  
  1602. ;;; {Module-based Loading}
  1603. ;;;
  1604.  
  1605. (define (save-module-excursion thunk)
  1606.   (let ((inner-module (current-module))
  1607.     (outer-module #f))
  1608.     (dynamic-wind (lambda ()
  1609.             (set! outer-module (current-module))
  1610.             (set-current-module inner-module)
  1611.             (set! inner-module #f))
  1612.           thunk
  1613.           (lambda ()
  1614.             (set! inner-module (current-module))
  1615.             (set-current-module outer-module)
  1616.             (set! outer-module #f)))))
  1617.  
  1618. (define basic-load load)
  1619.  
  1620. (define (load-module filename . reader)
  1621.   (save-module-excursion
  1622.    (lambda ()
  1623.      (let ((oldname (and (current-load-port)
  1624.              (port-filename (current-load-port)))))
  1625.        (apply basic-load
  1626.           (if (and oldname
  1627.                (> (string-length filename) 0)
  1628.                (not (char=? (string-ref filename 0) #\/))
  1629.                (not (string=? (dirname oldname) ".")))
  1630.           (string-append (dirname oldname) "/" filename)
  1631.           filename)
  1632.           reader)))))
  1633.  
  1634.  
  1635.  
  1636.  
  1637. ;;; {MODULE-REF -- exported}
  1638. ;;;
  1639.  
  1640. ;; Returns the value of a variable called NAME in MODULE or any of its
  1641. ;; used modules.  If there is no such variable, then if the optional third
  1642. ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
  1643. ;;
  1644. (define (module-ref module name . rest)
  1645.   (let ((variable (module-variable module name)))
  1646.     (if (and variable (variable-bound? variable))
  1647.     (variable-ref variable)
  1648.     (if (null? rest)
  1649.         (error "No variable named" name 'in module)
  1650.         (car rest)            ; default value
  1651.         ))))
  1652.  
  1653. ;; MODULE-SET! -- exported
  1654. ;;
  1655. ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
  1656. ;; to VALUE; if there is no such variable, an error is signaled.
  1657. ;;
  1658. (define (module-set! module name value)
  1659.   (let ((variable (module-variable module name)))
  1660.     (if variable
  1661.     (variable-set! variable value)
  1662.     (error "No variable named" name 'in module))))
  1663.  
  1664. ;; MODULE-DEFINE! -- exported
  1665. ;;
  1666. ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
  1667. ;; variable, it is added first.
  1668. ;;
  1669. (define (module-define! module name value)
  1670.   (let ((variable (module-local-variable module name)))
  1671.     (if variable
  1672.     (begin
  1673.       (variable-set! variable value)
  1674.       (module-modified module))
  1675.     (let ((variable (make-variable value)))
  1676.       (module-add! module name variable)))))
  1677.  
  1678. ;; MODULE-DEFINED? -- exported
  1679. ;;
  1680. ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
  1681. ;; uses)
  1682. ;;
  1683. (define (module-defined? module name)
  1684.   (let ((variable (module-variable module name)))
  1685.     (and variable (variable-bound? variable))))
  1686.  
  1687. ;; MODULE-USE! module interface
  1688. ;;
  1689. ;; Add INTERFACE to the list of interfaces used by MODULE.
  1690. ;;
  1691. (define (module-use! module interface)
  1692.   (set-module-uses! module
  1693.             (cons interface
  1694.               (filter (lambda (m)
  1695.                     (not (equal? (module-name m)
  1696.                          (module-name interface))))
  1697.                   (module-uses module))))
  1698.   (module-modified module))
  1699.  
  1700. ;; MODULE-USE-INTERFACES! module interfaces
  1701. ;;
  1702. ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
  1703. ;;
  1704. (define (module-use-interfaces! module interfaces)
  1705.   (let* ((duplicates-handlers? (or (module-duplicates-handlers module)
  1706.                    (default-duplicate-binding-procedures)))
  1707.      (uses (module-uses module)))
  1708.     ;; remove duplicates-interface
  1709.     (set! uses (delq! (module-duplicates-interface module) uses))
  1710.     ;; remove interfaces to be added
  1711.     (for-each (lambda (interface)
  1712.         (set! uses
  1713.               (filter (lambda (m)
  1714.                 (not (equal? (module-name m)
  1715.                          (module-name interface))))
  1716.                   uses)))
  1717.           interfaces)
  1718.     ;; add interfaces to use list
  1719.     (set-module-uses! module uses)
  1720.     (for-each (lambda (interface)
  1721.         (and duplicates-handlers?
  1722.              ;; perform duplicate checking
  1723.              (process-duplicates module interface))
  1724.         (set! uses (cons interface uses))
  1725.         (set-module-uses! module uses))
  1726.           interfaces)
  1727.     ;; add duplicates interface
  1728.     (if (module-duplicates-interface module)
  1729.     (set-module-uses! module
  1730.               (cons (module-duplicates-interface module) uses)))
  1731.     (module-modified module)))
  1732.  
  1733.  
  1734.  
  1735. ;;; {Recursive Namespaces}
  1736. ;;;
  1737. ;;; A hierarchical namespace emerges if we consider some module to be
  1738. ;;; root, and variables bound to modules as nested namespaces.
  1739. ;;;
  1740. ;;; The routines in this file manage variable names in hierarchical namespace.
  1741. ;;; Each variable name is a list of elements, looked up in successively nested
  1742. ;;; modules.
  1743. ;;;
  1744. ;;;        (nested-ref some-root-module '(foo bar baz))
  1745. ;;;        => <value of a variable named baz in the module bound to bar in
  1746. ;;;            the module bound to foo in some-root-module>
  1747. ;;;
  1748. ;;;
  1749. ;;; There are:
  1750. ;;;
  1751. ;;;    ;; a-root is a module
  1752. ;;;    ;; name is a list of symbols
  1753. ;;;
  1754. ;;;    nested-ref a-root name
  1755. ;;;    nested-set! a-root name val
  1756. ;;;    nested-define! a-root name val
  1757. ;;;    nested-remove! a-root name
  1758. ;;;
  1759. ;;;
  1760. ;;; (current-module) is a natural choice for a-root so for convenience there are
  1761. ;;; also:
  1762. ;;;
  1763. ;;;    local-ref name        ==    nested-ref (current-module) name
  1764. ;;;    local-set! name val    ==    nested-set! (current-module) name val
  1765. ;;;    local-define! name val    ==    nested-define! (current-module) name val
  1766. ;;;    local-remove! name    ==    nested-remove! (current-module) name
  1767. ;;;
  1768.  
  1769.  
  1770. (define (nested-ref root names)
  1771.   (let loop ((cur root)
  1772.          (elts names))
  1773.     (cond
  1774.      ((null? elts)        cur)
  1775.      ((not (module? cur))    #f)
  1776.      (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
  1777.  
  1778. (define (nested-set! root names val)
  1779.   (let loop ((cur root)
  1780.          (elts names))
  1781.     (if (null? (cdr elts))
  1782.     (module-set! cur (car elts) val)
  1783.     (loop (module-ref cur (car elts)) (cdr elts)))))
  1784.  
  1785. (define (nested-define! root names val)
  1786.   (let loop ((cur root)
  1787.          (elts names))
  1788.     (if (null? (cdr elts))
  1789.     (module-define! cur (car elts) val)
  1790.     (loop (module-ref cur (car elts)) (cdr elts)))))
  1791.  
  1792. (define (nested-remove! root names)
  1793.   (let loop ((cur root)
  1794.          (elts names))
  1795.     (if (null? (cdr elts))
  1796.     (module-remove! cur (car elts))
  1797.     (loop (module-ref cur (car elts)) (cdr elts)))))
  1798.  
  1799. (define (local-ref names) (nested-ref (current-module) names))
  1800. (define (local-set! names val) (nested-set! (current-module) names val))
  1801. (define (local-define names val) (nested-define! (current-module) names val))
  1802. (define (local-remove names) (nested-remove! (current-module) names))
  1803.  
  1804.  
  1805.  
  1806.  
  1807. ;;; {The (%app) module}
  1808. ;;;
  1809. ;;; The root of conventionally named objects not directly in the top level.
  1810. ;;;
  1811. ;;; (%app modules)
  1812. ;;; (%app modules guile)
  1813. ;;;
  1814. ;;; The directory of all modules and the standard root module.
  1815. ;;;
  1816.  
  1817. (define (module-public-interface m)
  1818.   (module-ref m '%module-public-interface #f))
  1819. (define (set-module-public-interface! m i)
  1820.   (module-define! m '%module-public-interface i))
  1821. (define (set-system-module! m s)
  1822.   (set-procedure-property! (module-eval-closure m) 'system-module s))
  1823. (define the-root-module (make-root-module))
  1824. (define the-scm-module (make-scm-module))
  1825. (set-module-public-interface! the-root-module the-scm-module)
  1826. (set-module-name! the-root-module '(guile))
  1827. (set-module-name! the-scm-module '(guile))
  1828. (set-module-kind! the-scm-module 'interface)
  1829. (for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
  1830.  
  1831. ;; NOTE: This binding is used in libguile/modules.c.
  1832. ;;
  1833. (define (make-modules-in module name)
  1834.   (if (null? name)
  1835.       module
  1836.       (cond
  1837.        ((module-ref module (car name) #f)
  1838.     => (lambda (m) (make-modules-in m (cdr name))))
  1839.        (else    (let ((m (make-module 31)))
  1840.           (set-module-kind! m 'directory)
  1841.           (set-module-name! m (append (or (module-name module)
  1842.                           '())
  1843.                           (list (car name))))
  1844.           (module-define! module (car name) m)
  1845.           (make-modules-in m (cdr name)))))))
  1846.  
  1847. (define (beautify-user-module! module)
  1848.   (let ((interface (module-public-interface module)))
  1849.     (if (or (not interface)
  1850.         (eq? interface module))
  1851.     (let ((interface (make-module 31)))
  1852.       (set-module-name! interface (module-name module))
  1853.       (set-module-kind! interface 'interface)
  1854.       (set-module-public-interface! module interface))))
  1855.   (if (and (not (memq the-scm-module (module-uses module)))
  1856.        (not (eq? module the-root-module)))
  1857.       (set-module-uses! module
  1858.             (append (module-uses module) (list the-scm-module)))))
  1859.  
  1860. ;; NOTE: This binding is used in libguile/modules.c.
  1861. ;;
  1862. (define (resolve-module name . maybe-autoload)
  1863.   (let ((full-name (append '(%app modules) name)))
  1864.     (let ((already (nested-ref the-root-module full-name)))
  1865.       (if already
  1866.       ;; The module already exists...
  1867.       (if (and (or (null? maybe-autoload) (car maybe-autoload))
  1868.            (not (module-public-interface already)))
  1869.           ;; ...but we are told to load and it doesn't contain source, so
  1870.           (begin
  1871.         (try-load-module name)
  1872.         already)
  1873.           ;; simply return it.
  1874.           already)
  1875.       (begin
  1876.         ;; Try to autoload it if we are told so
  1877.         (if (or (null? maybe-autoload) (car maybe-autoload))
  1878.         (try-load-module name))
  1879.         ;; Get/create it.
  1880.         (make-modules-in (current-module) full-name))))))
  1881.  
  1882. ;; Cheat.  These bindings are needed by modules.c, but we don't want
  1883. ;; to move their real definition here because that would be unnatural.
  1884. ;;
  1885. (define try-module-autoload #f)
  1886. (define process-define-module #f)
  1887. (define process-use-modules #f)
  1888. (define module-export! #f)
  1889.  
  1890. ;; This boots the module system.  All bindings needed by modules.c
  1891. ;; must have been defined by now.
  1892. ;;
  1893. (set-current-module the-root-module)
  1894.  
  1895. (define %app (make-module 31))
  1896. (define app %app) ;; for backwards compatability
  1897. (local-define '(%app modules) (make-module 31))
  1898. (local-define '(%app modules guile) the-root-module)
  1899.  
  1900. ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
  1901.  
  1902. (define (try-load-module name)
  1903.   (or (begin-deprecated (try-module-linked name))
  1904.       (try-module-autoload name)
  1905.       (begin-deprecated (try-module-dynamic-link name))))
  1906.  
  1907. (define (purify-module! module)
  1908.   "Removes bindings in MODULE which are inherited from the (guile) module."
  1909.   (let ((use-list (module-uses module)))
  1910.     (if (and (pair? use-list)
  1911.          (eq? (car (last-pair use-list)) the-scm-module))
  1912.     (set-module-uses! module (reverse (cdr (reverse use-list)))))))
  1913.  
  1914. ;; Return a module that is an interface to the module designated by
  1915. ;; NAME.
  1916. ;;
  1917. ;; `resolve-interface' takes four keyword arguments:
  1918. ;;
  1919. ;;   #:select SELECTION
  1920. ;;
  1921. ;; SELECTION is a list of binding-specs to be imported; A binding-spec
  1922. ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
  1923. ;; is the name in the used module and SEEN is the name in the using
  1924. ;; module.  Note that SEEN is also passed through RENAMER, below.  The
  1925. ;; default is to select all bindings.  If you specify no selection but
  1926. ;; a renamer, only the bindings that already exist in the used module
  1927. ;; are made available in the interface.  Bindings that are added later
  1928. ;; are not picked up.
  1929. ;;
  1930. ;;   #:hide BINDINGS
  1931. ;;
  1932. ;; BINDINGS is a list of bindings which should not be imported.
  1933. ;;
  1934. ;;   #:prefix PREFIX
  1935. ;;
  1936. ;; PREFIX is a symbol that will be appended to each exported name.
  1937. ;; The default is to not perform any renaming.
  1938. ;;
  1939. ;;   #:renamer RENAMER
  1940. ;;
  1941. ;; RENAMER is a procedure that takes a symbol and returns its new
  1942. ;; name.  The default is not perform any renaming.
  1943. ;;
  1944. ;; Signal "no code for module" error if module name is not resolvable
  1945. ;; or its public interface is not available.  Signal "no binding"
  1946. ;; error if selected binding does not exist in the used module.
  1947. ;;
  1948. (define (resolve-interface name . args)
  1949.  
  1950.   (define (get-keyword-arg args kw def)
  1951.     (cond ((memq kw args)
  1952.        => (lambda (kw-arg)
  1953.         (if (null? (cdr kw-arg))
  1954.             (error "keyword without value: " kw))
  1955.         (cadr kw-arg)))
  1956.       (else
  1957.        def)))
  1958.  
  1959.   (let* ((select (get-keyword-arg args #:select #f))
  1960.      (hide (get-keyword-arg args #:hide '()))
  1961.      (renamer (or (get-keyword-arg args #:renamer #f)
  1962.               (let ((prefix (get-keyword-arg args #:prefix #f)))
  1963.             (and prefix (symbol-prefix-proc prefix)))
  1964.               identity))
  1965.          (module (resolve-module name))
  1966.          (public-i (and module (module-public-interface module))))
  1967.     (and (or (not module) (not public-i))
  1968.          (error "no code for module" name))
  1969.     (if (and (not select) (null? hide) (eq? renamer identity))
  1970.         public-i
  1971.         (let ((selection (or select (module-map (lambda (sym var) sym)
  1972.                         public-i)))
  1973.               (custom-i (make-module 31)))
  1974.           (set-module-kind! custom-i 'custom-interface)
  1975.       (set-module-name! custom-i name)
  1976.       ;; XXX - should use a lazy binder so that changes to the
  1977.       ;; used module are picked up automatically.
  1978.       (for-each (lambda (bspec)
  1979.               (let* ((direct? (symbol? bspec))
  1980.                  (orig (if direct? bspec (car bspec)))
  1981.                  (seen (if direct? bspec (cdr bspec)))
  1982.                  (var (or (module-local-variable public-i orig)
  1983.                       (module-local-variable module orig)
  1984.                       (error
  1985.                        ;; fixme: format manually for now
  1986.                        (simple-format
  1987.                     #f "no binding `~A' in module ~A"
  1988.                     orig name)))))
  1989.             (if (memq orig hide)
  1990.                 (set! hide (delq! orig hide))
  1991.                 (module-add! custom-i
  1992.                      (renamer seen)
  1993.                      var))))
  1994.             selection)
  1995.       ;; Check that we are not hiding bindings which don't exist
  1996.       (for-each (lambda (binding)
  1997.               (if (not (module-local-variable public-i binding))
  1998.               (error
  1999.                (simple-format
  2000.                 #f "no binding `~A' to hide in module ~A"
  2001.                 binding name))))
  2002.             hide)
  2003.           custom-i))))
  2004.  
  2005. (define (symbol-prefix-proc prefix)
  2006.   (lambda (symbol)
  2007.     (symbol-append prefix symbol)))
  2008.  
  2009. ;; This function is called from "modules.c".  If you change it, be
  2010. ;; sure to update "modules.c" as well.
  2011.  
  2012. (define (process-define-module args)
  2013.   (let* ((module-id (car args))
  2014.          (module (resolve-module module-id #f))
  2015.          (kws (cdr args))
  2016.          (unrecognized (lambda (arg)
  2017.                          (error "unrecognized define-module argument" arg))))
  2018.     (beautify-user-module! module)
  2019.     (let loop ((kws kws)
  2020.            (reversed-interfaces '())
  2021.            (exports '())
  2022.            (re-exports '())
  2023.            (replacements '()))
  2024.  
  2025.       (if (null? kws)
  2026.       (call-with-deferred-observers
  2027.        (lambda ()
  2028.          (module-use-interfaces! module (reverse reversed-interfaces))
  2029.          (module-export! module exports)
  2030.          (module-replace! module replacements)
  2031.          (module-re-export! module re-exports)))
  2032.       (case (car kws)
  2033.         ((#:use-module #:use-syntax)
  2034.          (or (pair? (cdr kws))
  2035.          (unrecognized kws))
  2036.          (let* ((interface-args (cadr kws))
  2037.             (interface (apply resolve-interface interface-args)))
  2038.            (and (eq? (car kws) #:use-syntax)
  2039.             (or (symbol? (caar interface-args))
  2040.             (error "invalid module name for use-syntax"
  2041.                    (car interface-args)))
  2042.             (set-module-transformer!
  2043.              module
  2044.              (module-ref interface
  2045.                  (car (last-pair (car interface-args)))
  2046.                  #f)))
  2047.            (loop (cddr kws)
  2048.              (cons interface reversed-interfaces)
  2049.              exports
  2050.              re-exports
  2051.              replacements)))
  2052.         ((#:autoload)
  2053.          (or (and (pair? (cdr kws)) (pair? (cddr kws)))
  2054.          (unrecognized kws))
  2055.          (loop (cdddr kws)
  2056.            (cons (make-autoload-interface module
  2057.                           (cadr kws)
  2058.                           (caddr kws))
  2059.              reversed-interfaces)
  2060.            exports
  2061.            re-exports
  2062.            replacements))
  2063.         ((#:no-backtrace)
  2064.          (set-system-module! module #t)
  2065.          (loop (cdr kws) reversed-interfaces exports re-exports replacements))
  2066.         ((#:pure)
  2067.          (purify-module! module)
  2068.          (loop (cdr kws) reversed-interfaces exports re-exports replacements))
  2069.         ((#:duplicates)
  2070.          (if (not (pair? (cdr kws)))
  2071.          (unrecognized kws))
  2072.          (set-module-duplicates-handlers!
  2073.           module
  2074.           (lookup-duplicates-handlers (cadr kws)))
  2075.          (loop (cddr kws) reversed-interfaces exports re-exports replacements))
  2076.         ((#:export #:export-syntax)
  2077.          (or (pair? (cdr kws))
  2078.          (unrecognized kws))
  2079.          (loop (cddr kws)
  2080.            reversed-interfaces
  2081.            (append (cadr kws) exports)
  2082.            re-exports
  2083.            replacements))
  2084.         ((#:re-export #:re-export-syntax)
  2085.          (or (pair? (cdr kws))
  2086.          (unrecognized kws))
  2087.          (loop (cddr kws)
  2088.            reversed-interfaces
  2089.            exports
  2090.            (append (cadr kws) re-exports)
  2091.            replacements))
  2092.         ((#:replace #:replace-syntax)
  2093.          (or (pair? (cdr kws))
  2094.          (unrecognized kws))
  2095.          (loop (cddr kws)
  2096.            reversed-interfaces
  2097.            exports
  2098.            re-exports
  2099.            (append (cadr kws) replacements)))
  2100.         (else
  2101.          (unrecognized kws)))))
  2102.     (run-hook module-defined-hook module)
  2103.     module))
  2104.  
  2105. ;; `module-defined-hook' is a hook that is run whenever a new module
  2106. ;; is defined.  Its members are called with one argument, the new
  2107. ;; module.
  2108. (define module-defined-hook (make-hook 1))
  2109.  
  2110.  
  2111.  
  2112. ;;; {Autoload}
  2113. ;;;
  2114.  
  2115. (define (make-autoload-interface module name bindings)
  2116.   (let ((b (lambda (a sym definep)
  2117.          (and (memq sym bindings)
  2118.           (let ((i (module-public-interface (resolve-module name))))
  2119.             (if (not i)
  2120.             (error "missing interface for module" name))
  2121.             (let ((autoload (memq a (module-uses module))))
  2122.               ;; Replace autoload-interface with actual interface if
  2123.               ;; that has not happened yet.
  2124.               (if (pair? autoload)
  2125.               (set-car! autoload i)))
  2126.             (module-local-variable i sym))))))
  2127.     (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f #f
  2128.             '() (make-weak-value-hash-table 31) 0)))
  2129.  
  2130. ;;; {Compiled module}
  2131.  
  2132. (define load-compiled #f)
  2133.  
  2134.  
  2135.  
  2136. ;;; {Autoloading modules}
  2137. ;;;
  2138.  
  2139. (define autoloads-in-progress '())
  2140.  
  2141. ;; This function is called from "modules.c".  If you change it, be
  2142. ;; sure to update "modules.c" as well.
  2143.  
  2144. (define (try-module-autoload module-name)
  2145.   (let* ((reverse-name (reverse module-name))
  2146.      (name (symbol->string (car reverse-name)))
  2147.      (dir-hint-module-name (reverse (cdr reverse-name)))
  2148.      (dir-hint (apply string-append
  2149.               (map (lambda (elt)
  2150.                  (string-append (symbol->string elt) "/"))
  2151.                    dir-hint-module-name))))
  2152.     (resolve-module dir-hint-module-name #f)
  2153.     (and (not (autoload-done-or-in-progress? dir-hint name))
  2154.      (let ((didit #f))
  2155.        (define (load-file proc file)
  2156.          (save-module-excursion (lambda () (proc file)))
  2157.          (set! didit #t))
  2158.        (dynamic-wind
  2159.         (lambda () (autoload-in-progress! dir-hint name))
  2160.         (lambda ()
  2161.           (let ((file (in-vicinity dir-hint name)))
  2162.         (cond ((and load-compiled
  2163.                 (%search-load-path (string-append file ".go")))
  2164.                => (lambda (full)
  2165.                 (load-file load-compiled full)))
  2166.               ((%search-load-path file)
  2167.                => (lambda (full)
  2168.                 (with-fluids ((current-reader #f))
  2169.                   (load-file primitive-load full)))))))
  2170.         (lambda () (set-autoloaded! dir-hint name didit)))
  2171.        didit))))
  2172.  
  2173.  
  2174.  
  2175. ;;; {Dynamic linking of modules}
  2176. ;;;
  2177.  
  2178. (define autoloads-done '((guile . guile)))
  2179.  
  2180. (define (autoload-done-or-in-progress? p m)
  2181.   (let ((n (cons p m)))
  2182.     (->bool (or (member n autoloads-done)
  2183.         (member n autoloads-in-progress)))))
  2184.  
  2185. (define (autoload-done! p m)
  2186.   (let ((n (cons p m)))
  2187.     (set! autoloads-in-progress
  2188.       (delete! n autoloads-in-progress))
  2189.     (or (member n autoloads-done)
  2190.     (set! autoloads-done (cons n autoloads-done)))))
  2191.  
  2192. (define (autoload-in-progress! p m)
  2193.   (let ((n (cons p m)))
  2194.     (set! autoloads-done
  2195.       (delete! n autoloads-done))
  2196.     (set! autoloads-in-progress (cons n autoloads-in-progress))))
  2197.  
  2198. (define (set-autoloaded! p m done?)
  2199.   (if done?
  2200.       (autoload-done! p m)
  2201.       (let ((n (cons p m)))
  2202.     (set! autoloads-done (delete! n autoloads-done))
  2203.     (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
  2204.  
  2205.  
  2206.  
  2207. ;;; {Run-time options}
  2208. ;;;
  2209.  
  2210. (define define-option-interface
  2211.   (let* ((option-name car)
  2212.      (option-value cadr)
  2213.      (option-documentation caddr)
  2214.  
  2215.      (print-option (lambda (option)
  2216.              (display (option-name option))
  2217.              (if (< (string-length
  2218.                  (symbol->string (option-name option)))
  2219.                 8)
  2220.                  (display #\tab))
  2221.              (display #\tab)
  2222.              (display (option-value option))
  2223.              (display #\tab)
  2224.              (display (option-documentation option))
  2225.              (newline)))
  2226.  
  2227.      ;; Below follow the macros defining the run-time option interfaces.
  2228.  
  2229.      (make-options (lambda (interface)
  2230.              `(lambda args
  2231.                 (cond ((null? args) (,interface))
  2232.                   ((list? (car args))
  2233.                    (,interface (car args)) (,interface))
  2234.                   (else (for-each ,print-option
  2235.                           (,interface #t)))))))
  2236.  
  2237.      (make-enable (lambda (interface)
  2238.             `(lambda flags
  2239.                (,interface (append flags (,interface)))
  2240.                (,interface))))
  2241.  
  2242.      (make-disable (lambda (interface)
  2243.              `(lambda flags
  2244.                 (let ((options (,interface)))
  2245.                   (for-each (lambda (flag)
  2246.                       (set! options (delq! flag options)))
  2247.                     flags)
  2248.                   (,interface options)
  2249.                   (,interface))))))
  2250.     (procedure->memoizing-macro
  2251.      (lambda (exp env)
  2252.        (let* ((option-group (cadr exp))
  2253.           (interface (car option-group))
  2254.           (options/enable/disable (cadr option-group)))
  2255.      `(begin
  2256.         (define ,(car options/enable/disable)
  2257.           ,(make-options interface))
  2258.         (define ,(cadr options/enable/disable)
  2259.           ,(make-enable interface))
  2260.         (define ,(caddr options/enable/disable)
  2261.           ,(make-disable interface))
  2262.         (defmacro ,(caaddr option-group) (opt val)
  2263.           `(,,(car options/enable/disable)
  2264.         (append (,,(car options/enable/disable))
  2265.             (list ',opt ,val))))))))))
  2266.  
  2267. (define-option-interface
  2268.   (eval-options-interface
  2269.    (eval-options eval-enable eval-disable)
  2270.    (eval-set!)))
  2271.  
  2272. (define-option-interface
  2273.   (debug-options-interface
  2274.    (debug-options debug-enable debug-disable)
  2275.    (debug-set!)))
  2276.  
  2277. (define-option-interface
  2278.   (evaluator-traps-interface
  2279.    (traps trap-enable trap-disable)
  2280.    (trap-set!)))
  2281.  
  2282. (define-option-interface
  2283.   (read-options-interface
  2284.    (read-options read-enable read-disable)
  2285.    (read-set!)))
  2286.  
  2287. (define-option-interface
  2288.   (print-options-interface
  2289.    (print-options print-enable print-disable)
  2290.    (print-set!)))
  2291.  
  2292.  
  2293.  
  2294. ;;; {Running Repls}
  2295. ;;;
  2296.  
  2297. (define (repl read evaler print)
  2298.   (let loop ((source (read (current-input-port))))
  2299.     (print (evaler source))
  2300.     (loop (read (current-input-port)))))
  2301.  
  2302. ;; A provisional repl that acts like the SCM repl:
  2303. ;;
  2304. (define scm-repl-silent #f)
  2305. (define (assert-repl-silence v) (set! scm-repl-silent v))
  2306.  
  2307. (define *unspecified* (if #f #f))
  2308. (define (unspecified? v) (eq? v *unspecified*))
  2309.  
  2310. (define scm-repl-print-unspecified #f)
  2311. (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
  2312.  
  2313. (define scm-repl-verbose #f)
  2314. (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
  2315.  
  2316. (define scm-repl-prompt "guile> ")
  2317.  
  2318. (define (set-repl-prompt! v) (set! scm-repl-prompt v))
  2319.  
  2320. (define (default-lazy-handler key . args)
  2321.   (save-stack lazy-handler-dispatch)
  2322.   (apply throw key args))
  2323.  
  2324. (define (lazy-handler-dispatch key . args)
  2325.   (apply default-lazy-handler key args))
  2326.  
  2327. (define abort-hook (make-hook))
  2328.  
  2329. ;; these definitions are used if running a script.
  2330. ;; otherwise redefined in error-catching-loop.
  2331. (define (set-batch-mode?! arg) #t)
  2332. (define (batch-mode?) #t)
  2333.  
  2334. (define (error-catching-loop thunk)
  2335.   (let ((status #f)
  2336.     (interactive #t))
  2337.     (define (loop first)
  2338.       (let ((next
  2339.          (catch #t
  2340.  
  2341.             (lambda ()
  2342.               (call-with-unblocked-asyncs
  2343.                (lambda ()
  2344.              (with-traps
  2345.               (lambda ()
  2346.                 (first)
  2347.  
  2348.                 ;; This line is needed because mark
  2349.                 ;; doesn't do closures quite right.
  2350.                 ;; Unreferenced locals should be
  2351.                 ;; collected.
  2352.                 (set! first #f)
  2353.                 (let loop ((v (thunk)))
  2354.                   (loop (thunk)))
  2355.                 #f)))))
  2356.  
  2357.             (lambda (key . args)
  2358.               (case key
  2359.             ((quit)
  2360.              (set! status args)
  2361.              #f)
  2362.  
  2363.             ((switch-repl)
  2364.              (apply throw 'switch-repl args))
  2365.  
  2366.             ((abort)
  2367.              ;; This is one of the closures that require
  2368.              ;; (set! first #f) above
  2369.              ;;
  2370.              (lambda ()
  2371.                (run-hook abort-hook)
  2372.                (force-output (current-output-port))
  2373.                (display "ABORT: "  (current-error-port))
  2374.                (write args (current-error-port))
  2375.                (newline (current-error-port))
  2376.                (if interactive
  2377.                    (begin
  2378.                  (if (and
  2379.                       (not has-shown-debugger-hint?)
  2380.                       (not (memq 'backtrace
  2381.                          (debug-options-interface)))
  2382.                       (stack? (fluid-ref the-last-stack)))
  2383.                      (begin
  2384.                        (newline (current-error-port))
  2385.                        (display
  2386.                     "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
  2387.                     (current-error-port))
  2388.                        (set! has-shown-debugger-hint? #t)))
  2389.                  (force-output (current-error-port)))
  2390.                    (begin
  2391.                  (primitive-exit 1)))
  2392.                (set! stack-saved? #f)))
  2393.  
  2394.             (else
  2395.              ;; This is the other cons-leak closure...
  2396.              (lambda ()
  2397.                (cond ((= (length args) 4)
  2398.                   (apply handle-system-error key args))
  2399.                  (else
  2400.                   (apply bad-throw key args)))))))
  2401.  
  2402.             ;; Note that having just `lazy-handler-dispatch'
  2403.             ;; here is connected with the mechanism that
  2404.             ;; produces a nice backtrace upon error.  If, for
  2405.             ;; example, this is replaced with (lambda args
  2406.             ;; (apply lazy-handler-dispatch args)), the stack
  2407.             ;; cutting (in save-stack) goes wrong and ends up
  2408.             ;; saving no stack at all, so there is no
  2409.             ;; backtrace.
  2410.             lazy-handler-dispatch)))
  2411.  
  2412.     (if next (loop next) status)))
  2413.     (set! set-batch-mode?! (lambda (arg)
  2414.                  (cond (arg
  2415.                     (set! interactive #f)
  2416.                     (restore-signals))
  2417.                    (#t
  2418.                     (error "sorry, not implemented")))))
  2419.     (set! batch-mode? (lambda () (not interactive)))
  2420.     (call-with-blocked-asyncs
  2421.      (lambda () (loop (lambda () #t))))))
  2422.  
  2423. ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
  2424. (define before-signal-stack (make-fluid))
  2425. (define stack-saved? #f)
  2426.  
  2427. (define (save-stack . narrowing)
  2428.   (or stack-saved?
  2429.       (cond ((not (memq 'debug (debug-options-interface)))
  2430.          (fluid-set! the-last-stack #f)
  2431.          (set! stack-saved? #t))
  2432.         (else
  2433.          (fluid-set!
  2434.           the-last-stack
  2435.           (case (stack-id #t)
  2436.         ((repl-stack)
  2437.          (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
  2438.         ((load-stack)
  2439.          (apply make-stack #t save-stack 0 #t 0 narrowing))
  2440.         ((tk-stack)
  2441.          (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
  2442.         ((#t)
  2443.          (apply make-stack #t save-stack 0 1 narrowing))
  2444.         (else
  2445.          (let ((id (stack-id #t)))
  2446.            (and (procedure? id)
  2447.             (apply make-stack #t save-stack id #t 0 narrowing))))))
  2448.          (set! stack-saved? #t)))))
  2449.  
  2450. (define before-error-hook (make-hook))
  2451. (define after-error-hook (make-hook))
  2452. (define before-backtrace-hook (make-hook))
  2453. (define after-backtrace-hook (make-hook))
  2454.  
  2455. (define has-shown-debugger-hint? #f)
  2456.  
  2457. (define (handle-system-error key . args)
  2458.   (let ((cep (current-error-port)))
  2459.     (cond ((not (stack? (fluid-ref the-last-stack))))
  2460.       ((memq 'backtrace (debug-options-interface))
  2461.        (let ((highlights (if (or (eq? key 'wrong-type-arg)
  2462.                      (eq? key 'out-of-range))
  2463.                  (list-ref args 3)
  2464.                  '())))
  2465.          (run-hook before-backtrace-hook)
  2466.          (newline cep)
  2467.          (display "Backtrace:\n")
  2468.          (display-backtrace (fluid-ref the-last-stack) cep
  2469.                 #f #f highlights)
  2470.          (newline cep)
  2471.          (run-hook after-backtrace-hook))))
  2472.     (run-hook before-error-hook)
  2473.     (apply display-error (fluid-ref the-last-stack) cep args)
  2474.     (run-hook after-error-hook)
  2475.     (force-output cep)
  2476.     (throw 'abort key)))
  2477.  
  2478. (define (quit . args)
  2479.   (apply throw 'quit args))
  2480.  
  2481. (define exit quit)
  2482.  
  2483. ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
  2484.  
  2485. ;; Replaced by C code:
  2486. ;;(define (backtrace)
  2487. ;;  (if (fluid-ref the-last-stack)
  2488. ;;      (begin
  2489. ;;    (newline)
  2490. ;;    (display-backtrace (fluid-ref the-last-stack) (current-output-port))
  2491. ;;    (newline)
  2492. ;;    (if (and (not has-shown-backtrace-hint?)
  2493. ;;         (not (memq 'backtrace (debug-options-interface))))
  2494. ;;        (begin
  2495. ;;          (display
  2496. ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
  2497. ;;automatically if an error occurs in the future.\n")
  2498. ;;          (set! has-shown-backtrace-hint? #t))))
  2499. ;;      (display "No backtrace available.\n")))
  2500.  
  2501. (define (error-catching-repl r e p)
  2502.   (error-catching-loop
  2503.    (lambda ()
  2504.      (call-with-values (lambda () (e (r)))
  2505.        (lambda the-values (for-each p the-values))))))
  2506.  
  2507. (define (gc-run-time)
  2508.   (cdr (assq 'gc-time-taken (gc-stats))))
  2509.  
  2510. (define before-read-hook (make-hook))
  2511. (define after-read-hook (make-hook))
  2512. (define before-eval-hook (make-hook 1))
  2513. (define after-eval-hook (make-hook 1))
  2514. (define before-print-hook (make-hook 1))
  2515. (define after-print-hook (make-hook 1))
  2516.  
  2517. ;;; The default repl-reader function.  We may override this if we've
  2518. ;;; the readline library.
  2519. (define repl-reader
  2520.   (lambda (prompt)
  2521.     (display prompt)
  2522.     (force-output)
  2523.     (run-hook before-read-hook)
  2524.     ((or (fluid-ref current-reader) read) (current-input-port))))
  2525.  
  2526. (define (scm-style-repl)
  2527.  
  2528.   (letrec (
  2529.        (start-gc-rt #f)
  2530.        (start-rt #f)
  2531.        (repl-report-start-timing (lambda ()
  2532.                        (set! start-gc-rt (gc-run-time))
  2533.                        (set! start-rt (get-internal-run-time))))
  2534.        (repl-report (lambda ()
  2535.               (display ";;; ")
  2536.               (display (inexact->exact
  2537.                     (* 1000 (/ (- (get-internal-run-time) start-rt)
  2538.                            internal-time-units-per-second))))
  2539.               (display "  msec  (")
  2540.               (display  (inexact->exact
  2541.                      (* 1000 (/ (- (gc-run-time) start-gc-rt)
  2542.                         internal-time-units-per-second))))
  2543.               (display " msec in gc)\n")))
  2544.  
  2545.        (consume-trailing-whitespace
  2546.         (lambda ()
  2547.           (let ((ch (peek-char)))
  2548.         (cond
  2549.          ((eof-object? ch))
  2550.          ((or (char=? ch #\space) (char=? ch #\tab))
  2551.           (read-char)
  2552.           (consume-trailing-whitespace))
  2553.          ((char=? ch #\newline)
  2554.           (read-char))))))
  2555.        (-read (lambda ()
  2556.             (let ((val
  2557.                (let ((prompt (cond ((string? scm-repl-prompt)
  2558.                         scm-repl-prompt)
  2559.                            ((thunk? scm-repl-prompt)
  2560.                         (scm-repl-prompt))
  2561.                            (scm-repl-prompt "> ")
  2562.                            (else ""))))
  2563.                  (repl-reader prompt))))
  2564.  
  2565.               ;; As described in R4RS, the READ procedure updates the
  2566.               ;; port to point to the first character past the end of
  2567.               ;; the external representation of the object.  This
  2568.               ;; means that it doesn't consume the newline typically
  2569.               ;; found after an expression.  This means that, when
  2570.               ;; debugging Guile with GDB, GDB gets the newline, which
  2571.               ;; it often interprets as a "continue" command, making
  2572.               ;; breakpoints kind of useless.  So, consume any
  2573.               ;; trailing newline here, as well as any whitespace
  2574.               ;; before it.
  2575.               ;; But not if EOF, for control-D.
  2576.               (if (not (eof-object? val))
  2577.               (consume-trailing-whitespace))
  2578.               (run-hook after-read-hook)
  2579.               (if (eof-object? val)
  2580.               (begin
  2581.                 (repl-report-start-timing)
  2582.                 (if scm-repl-verbose
  2583.                 (begin
  2584.                   (newline)
  2585.                   (display ";;; EOF -- quitting")
  2586.                   (newline)))
  2587.                 (quit 0)))
  2588.               val)))
  2589.  
  2590.        (-eval (lambda (sourc)
  2591.             (repl-report-start-timing)
  2592.             (run-hook before-eval-hook sourc)
  2593.             (let ((val (start-stack 'repl-stack
  2594.                         ;; If you change this procedure
  2595.                         ;; (primitive-eval), please also
  2596.                         ;; modify the repl-stack case in
  2597.                         ;; save-stack so that stack cutting
  2598.                         ;; continues to work.
  2599.                         (primitive-eval sourc))))
  2600.               (run-hook after-eval-hook sourc)
  2601.               val)))
  2602.  
  2603.  
  2604.        (-print (let ((maybe-print (lambda (result)
  2605.                     (if (or scm-repl-print-unspecified
  2606.                         (not (unspecified? result)))
  2607.                         (begin
  2608.                           (write result)
  2609.                           (newline))))))
  2610.              (lambda (result)
  2611.                (if (not scm-repl-silent)
  2612.                (begin
  2613.                  (run-hook before-print-hook result)
  2614.                  (maybe-print result)
  2615.                  (run-hook after-print-hook result)
  2616.                  (if scm-repl-verbose
  2617.                  (repl-report))
  2618.                  (force-output))))))
  2619.  
  2620.        (-quit (lambda (args)
  2621.             (if scm-repl-verbose
  2622.             (begin
  2623.               (display ";;; QUIT executed, repl exitting")
  2624.               (newline)
  2625.               (repl-report)))
  2626.             args))
  2627.  
  2628.        (-abort (lambda ()
  2629.              (if scm-repl-verbose
  2630.              (begin
  2631.                (display ";;; ABORT executed.")
  2632.                (newline)
  2633.                (repl-report)))
  2634.              (repl -read -eval -print))))
  2635.  
  2636.     (let ((status (error-catching-repl -read
  2637.                        -eval
  2638.                        -print)))
  2639.       (-quit status))))
  2640.  
  2641.  
  2642.  
  2643.  
  2644. ;;; {IOTA functions: generating lists of numbers}
  2645. ;;;
  2646.  
  2647. (define (iota n)
  2648.   (let loop ((count (1- n)) (result '()))
  2649.     (if (< count 0) result
  2650.         (loop (1- count) (cons count result)))))
  2651.  
  2652.  
  2653.  
  2654. ;;; {collect}
  2655. ;;;
  2656. ;;; Similar to `begin' but returns a list of the results of all constituent
  2657. ;;; forms instead of the result of the last form.
  2658. ;;; (The definition relies on the current left-to-right
  2659. ;;;  order of evaluation of operands in applications.)
  2660. ;;;
  2661.  
  2662. (defmacro collect forms
  2663.   (cons 'list forms))
  2664.  
  2665.  
  2666.  
  2667. ;;; {with-fluids}
  2668. ;;;
  2669.  
  2670. ;; with-fluids is a convenience wrapper for the builtin procedure
  2671. ;; `with-fluids*'.  The syntax is just like `let':
  2672. ;;
  2673. ;;  (with-fluids ((fluid val)
  2674. ;;                ...)
  2675. ;;     body)
  2676.  
  2677. (defmacro with-fluids (bindings . body)
  2678.   (let ((fluids (map car bindings))
  2679.     (values (map cadr bindings)))
  2680.     (if (and (= (length fluids) 1) (= (length values) 1))
  2681.     `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
  2682.     `(with-fluids* (list ,@fluids) (list ,@values)
  2683.                (lambda () ,@body)))))
  2684.  
  2685.  
  2686.  
  2687. ;;; {Macros}
  2688. ;;;
  2689.  
  2690. ;; actually....hobbit might be able to hack these with a little
  2691. ;; coaxing
  2692. ;;
  2693.  
  2694. (define (primitive-macro? m)
  2695.   (and (macro? m)
  2696.        (not (macro-transformer m))))
  2697.  
  2698. (defmacro define-macro (first . rest)
  2699.   (let ((name (if (symbol? first) first (car first)))
  2700.     (transformer
  2701.      (if (symbol? first)
  2702.          (car rest)
  2703.          `(lambda ,(cdr first) ,@rest))))
  2704.     `(eval-case
  2705.       ((load-toplevel)
  2706.        (define ,name (defmacro:transformer ,transformer)))
  2707.       (else
  2708.        (error "define-macro can only be used at the top level")))))
  2709.  
  2710.  
  2711. (defmacro define-syntax-macro (first . rest)
  2712.   (let ((name (if (symbol? first) first (car first)))
  2713.     (transformer
  2714.      (if (symbol? first)
  2715.          (car rest)
  2716.          `(lambda ,(cdr first) ,@rest))))
  2717.     `(eval-case
  2718.       ((load-toplevel)
  2719.        (define ,name (defmacro:syntax-transformer ,transformer)))
  2720.       (else
  2721.        (error "define-syntax-macro can only be used at the top level")))))
  2722.  
  2723.  
  2724.  
  2725. ;;; {While}
  2726. ;;;
  2727. ;;; with `continue' and `break'.
  2728. ;;;
  2729.  
  2730. ;; The inner `do' loop avoids re-establishing a catch every iteration,
  2731. ;; that's only necessary if continue is actually used.  A new key is
  2732. ;; generated every time, so break and continue apply to their originating
  2733. ;; `while' even when recursing.  `while-helper' is an easy way to keep the
  2734. ;; `key' binding away from the cond and body code.
  2735. ;;
  2736. ;; FIXME: This is supposed to have an `unquote' on the `do' the same used
  2737. ;; for lambda and not, so as to protect against any user rebinding of that
  2738. ;; symbol, but unfortunately an unquote breaks with ice-9 syncase, eg.
  2739. ;;
  2740. ;;     (use-modules (ice-9 syncase))
  2741. ;;     (while #f)
  2742. ;;     => ERROR: invalid syntax ()
  2743. ;;
  2744. ;; This is probably a bug in syncase.
  2745. ;;
  2746. (define-macro (while cond . body)
  2747.   (define (while-helper proc)
  2748.     (do ((key (make-symbol "while-key")))
  2749.     ((catch key
  2750.         (lambda ()
  2751.           (proc (lambda () (throw key #t))
  2752.             (lambda () (throw key #f))))
  2753.         (lambda (key arg) arg)))))
  2754.   `(,while-helper (,lambda (break continue)
  2755.             (do ()
  2756.             ((,not ,cond))
  2757.               ,@body)
  2758.             #t)))
  2759.  
  2760.  
  2761.  
  2762.  
  2763. ;;; {Module System Macros}
  2764. ;;;
  2765.  
  2766. ;; Return a list of expressions that evaluate to the appropriate
  2767. ;; arguments for resolve-interface according to SPEC.
  2768.  
  2769. (define (compile-interface-spec spec)
  2770.   (define (make-keyarg sym key quote?)
  2771.     (cond ((or (memq sym spec)
  2772.            (memq key spec))
  2773.        => (lambda (rest)
  2774.         (if quote?
  2775.             (list key (list 'quote (cadr rest)))
  2776.             (list key (cadr rest)))))
  2777.       (else
  2778.        '())))
  2779.   (define (map-apply func list)
  2780.     (map (lambda (args) (apply func args)) list))
  2781.   (define keys
  2782.     ;; sym     key      quote?
  2783.     '((:select #:select #t)
  2784.       (:hide   #:hide    #t)
  2785.       (:prefix #:prefix #t)
  2786.       (:renamer #:renamer #f)))
  2787.   (if (not (pair? (car spec)))
  2788.       `(',spec)
  2789.       `(',(car spec)
  2790.     ,@(apply append (map-apply make-keyarg keys)))))
  2791.  
  2792. (define (keyword-like-symbol->keyword sym)
  2793.   (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
  2794.  
  2795. (define (compile-define-module-args args)
  2796.   ;; Just quote everything except #:use-module and #:use-syntax.  We
  2797.   ;; need to know about all arguments regardless since we want to turn
  2798.   ;; symbols that look like keywords into real keywords, and the
  2799.   ;; keyword args in a define-module form are not regular
  2800.   ;; (i.e. no-backtrace doesn't take a value).
  2801.   (let loop ((compiled-args `((quote ,(car args))))
  2802.          (args (cdr args)))
  2803.     (cond ((null? args)
  2804.        (reverse! compiled-args))
  2805.       ;; symbol in keyword position
  2806.       ((symbol? (car args))
  2807.        (loop compiled-args
  2808.          (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
  2809.       ((memq (car args) '(#:no-backtrace #:pure))
  2810.        (loop (cons (car args) compiled-args)
  2811.          (cdr args)))
  2812.       ((null? (cdr args))
  2813.        (error "keyword without value:" (car args)))
  2814.       ((memq (car args) '(#:use-module #:use-syntax))
  2815.        (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
  2816.             (car args)
  2817.             compiled-args)
  2818.          (cddr args)))
  2819.       ((eq? (car args) #:autoload)
  2820.        (loop (cons* `(quote ,(caddr args))
  2821.             `(quote ,(cadr args))
  2822.             (car args)
  2823.             compiled-args)
  2824.          (cdddr args)))
  2825.       (else
  2826.        (loop (cons* `(quote ,(cadr args))
  2827.             (car args)
  2828.             compiled-args)
  2829.          (cddr args))))))
  2830.  
  2831. (defmacro define-module args
  2832.   `(eval-case
  2833.     ((load-toplevel)
  2834.      (let ((m (process-define-module
  2835.            (list ,@(compile-define-module-args args)))))
  2836.        (set-current-module m)
  2837.        m))
  2838.     (else
  2839.      (error "define-module can only be used at the top level"))))
  2840.  
  2841. ;; The guts of the use-modules macro.  Add the interfaces of the named
  2842. ;; modules to the use-list of the current module, in order.
  2843.  
  2844. ;; This function is called by "modules.c".  If you change it, be sure
  2845. ;; to change scm_c_use_module as well.
  2846.  
  2847. (define (process-use-modules module-interface-args)
  2848.   (let ((interfaces (map (lambda (mif-args)
  2849.                (or (apply resolve-interface mif-args)
  2850.                    (error "no such module" mif-args)))
  2851.              module-interface-args)))
  2852.     (call-with-deferred-observers
  2853.      (lambda ()
  2854.        (module-use-interfaces! (current-module) interfaces)))))
  2855.  
  2856. (defmacro use-modules modules
  2857.   `(eval-case
  2858.     ((load-toplevel)
  2859.      (process-use-modules
  2860.       (list ,@(map (lambda (m)
  2861.              `(list ,@(compile-interface-spec m)))
  2862.            modules)))
  2863.      *unspecified*)
  2864.     (else
  2865.      (error "use-modules can only be used at the top level"))))
  2866.  
  2867. (defmacro use-syntax (spec)
  2868.   `(eval-case
  2869.     ((load-toplevel)
  2870.      ,@(if (pair? spec)
  2871.        `((process-use-modules (list
  2872.                    (list ,@(compile-interface-spec spec))))
  2873.          (set-module-transformer! (current-module)
  2874.                       ,(car (last-pair spec))))
  2875.        `((set-module-transformer! (current-module) ,spec)))
  2876.      *unspecified*)
  2877.     (else
  2878.      (error "use-syntax can only be used at the top level"))))
  2879.  
  2880. ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
  2881. ;; as soon as guile supports hygienic macros.
  2882. (define define-private define)
  2883.  
  2884. (defmacro define-public args
  2885.   (define (syntax)
  2886.     (error "bad syntax" (list 'define-public args)))
  2887.   (define (defined-name n)
  2888.     (cond
  2889.      ((symbol? n) n)
  2890.      ((pair? n) (defined-name (car n)))
  2891.      (else (syntax))))
  2892.   (cond
  2893.    ((null? args)
  2894.     (syntax))
  2895.    (#t
  2896.     (let ((name (defined-name (car args))))
  2897.       `(begin
  2898.      (define-private ,@args)
  2899.      (eval-case ((load-toplevel) (export ,name))))))))
  2900.  
  2901. (defmacro defmacro-public args
  2902.   (define (syntax)
  2903.     (error "bad syntax" (list 'defmacro-public args)))
  2904.   (define (defined-name n)
  2905.     (cond
  2906.      ((symbol? n) n)
  2907.      (else (syntax))))
  2908.   (cond
  2909.    ((null? args)
  2910.     (syntax))
  2911.    (#t
  2912.     (let ((name (defined-name (car args))))
  2913.       `(begin
  2914.      (eval-case ((load-toplevel) (export-syntax ,name)))
  2915.      (defmacro ,@args))))))
  2916.  
  2917. ;; Export a local variable
  2918.  
  2919. ;; This function is called from "modules.c".  If you change it, be
  2920. ;; sure to update "modules.c" as well.
  2921.  
  2922. (define (module-export! m names)
  2923.   (let ((public-i (module-public-interface m)))
  2924.     (for-each (lambda (name)
  2925.         (let ((var (module-ensure-local-variable! m name)))
  2926.           (module-add! public-i name var)))
  2927.           names)))
  2928.  
  2929. (define (module-replace! m names)
  2930.   (let ((public-i (module-public-interface m)))
  2931.     (for-each (lambda (name)
  2932.         (let ((var (module-ensure-local-variable! m name)))
  2933.           (set-object-property! var 'replace #t)
  2934.           (module-add! public-i name var)))
  2935.           names)))
  2936.  
  2937. ;; Re-export a imported variable
  2938. ;;
  2939. (define (module-re-export! m names)
  2940.   (let ((public-i (module-public-interface m)))
  2941.     (for-each (lambda (name)
  2942.         (let ((var (module-variable m name)))
  2943.           (cond ((not var)
  2944.              (error "Undefined variable:" name))
  2945.             ((eq? var (module-local-variable m name))
  2946.              (error "re-exporting local variable:" name))
  2947.             (else
  2948.              (module-add! public-i name var)))))
  2949.           names)))
  2950.  
  2951. (defmacro export names
  2952.   `(eval-case
  2953.     ((load-toplevel)
  2954.      (call-with-deferred-observers
  2955.       (lambda ()
  2956.     (module-export! (current-module) ',names))))
  2957.     (else
  2958.      (error "export can only be used at the top level"))))
  2959.  
  2960. (defmacro re-export names
  2961.   `(eval-case
  2962.     ((load-toplevel)
  2963.      (call-with-deferred-observers
  2964.       (lambda ()
  2965.     (module-re-export! (current-module) ',names))))
  2966.     (else
  2967.      (error "re-export can only be used at the top level"))))
  2968.  
  2969. (defmacro export-syntax names
  2970.   `(export ,@names))
  2971.  
  2972. (defmacro re-export-syntax names
  2973.   `(re-export ,@names))
  2974.  
  2975. (define load load-module)
  2976.  
  2977. ;; The following macro allows one to write, for example,
  2978. ;;
  2979. ;;    (@ (ice-9 pretty-print) pretty-print)
  2980. ;;
  2981. ;; to refer directly to the pretty-print variable in module (ice-9
  2982. ;; pretty-print).  It works by looking up the variable and inserting
  2983. ;; it directly into the code.  This is understood by the evaluator.
  2984. ;; Indeed, all references to global variables are memoized into such
  2985. ;; variable objects.
  2986.  
  2987. (define-macro (@ mod-name var-name)
  2988.   (let ((var (module-variable (resolve-interface mod-name) var-name)))
  2989.     (if (not var)
  2990.     (error "no such public variable" (list '@ mod-name var-name)))
  2991.     var))
  2992.  
  2993. ;; The '@@' macro is like '@' but it can also access bindings that
  2994. ;; have not been explicitely exported.
  2995.  
  2996. (define-macro (@@ mod-name var-name)
  2997.   (let ((var (module-variable (resolve-module mod-name) var-name)))
  2998.     (if (not var)
  2999.     (error "no such variable" (list '@@ mod-name var-name)))
  3000.     var))
  3001.  
  3002.  
  3003.  
  3004. ;;; {Parameters}
  3005. ;;;
  3006.  
  3007. (define make-mutable-parameter
  3008.   (let ((make (lambda (fluid converter)
  3009.         (lambda args
  3010.           (if (null? args)
  3011.               (fluid-ref fluid)
  3012.               (fluid-set! fluid (converter (car args))))))))
  3013.     (lambda (init . converter)
  3014.       (let ((fluid (make-fluid))
  3015.         (converter (if (null? converter)
  3016.                identity
  3017.                (car converter))))
  3018.     (fluid-set! fluid (converter init))
  3019.     (make fluid converter)))))
  3020.  
  3021.  
  3022.  
  3023. ;;; {Handling of duplicate imported bindings}
  3024. ;;;
  3025.  
  3026. ;; Duplicate handlers take the following arguments:
  3027. ;;
  3028. ;; module  importing module
  3029. ;; name       conflicting name
  3030. ;; int1       old interface where name occurs
  3031. ;; val1       value of binding in old interface
  3032. ;; int2       new interface where name occurs
  3033. ;; val2       value of binding in new interface
  3034. ;; var       previous resolution or #f
  3035. ;; val       value of previous resolution
  3036. ;;
  3037. ;; A duplicate handler can take three alternative actions:
  3038. ;;
  3039. ;; 1. return #f => leave responsibility to next handler
  3040. ;; 2. exit with an error
  3041. ;; 3. return a variable resolving the conflict
  3042. ;;
  3043.  
  3044. (define duplicate-handlers
  3045.   (let ((m (make-module 7)))
  3046.     
  3047.     (define (check module name int1 val1 int2 val2 var val)
  3048.       (scm-error 'misc-error
  3049.          #f
  3050.          "~A: `~A' imported from both ~A and ~A"
  3051.          (list (module-name module)
  3052.                name
  3053.                (module-name int1)
  3054.                (module-name int2))
  3055.          #f))
  3056.     
  3057.     (define (warn module name int1 val1 int2 val2 var val)
  3058.       (format (current-error-port)
  3059.           "WARNING: ~A: `~A' imported from both ~A and ~A\n"
  3060.           (module-name module)
  3061.           name
  3062.           (module-name int1)
  3063.           (module-name int2))
  3064.       #f)
  3065.      
  3066.     (define (replace module name int1 val1 int2 val2 var val)
  3067.       (let ((old (or (and var (object-property var 'replace) var)
  3068.              (module-variable int1 name)))
  3069.         (new (module-variable int2 name)))
  3070.     (if (object-property old 'replace)
  3071.         (and (or (eq? old new)
  3072.              (not (object-property new 'replace)))
  3073.          old)
  3074.         (and (object-property new 'replace)
  3075.          new))))
  3076.     
  3077.     (define (warn-override-core module name int1 val1 int2 val2 var val)
  3078.       (and (eq? int1 the-scm-module)
  3079.        (begin
  3080.          (format (current-error-port)
  3081.              "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
  3082.              (module-name module)
  3083.              (module-name int2)
  3084.              name)
  3085.          (module-local-variable int2 name))))
  3086.      
  3087.     (define (first module name int1 val1 int2 val2 var val)
  3088.       (or var (module-local-variable int1 name)))
  3089.      
  3090.     (define (last module name int1 val1 int2 val2 var val)
  3091.       (module-local-variable int2 name))
  3092.      
  3093.     (define (noop module name int1 val1 int2 val2 var val)
  3094.       #f)
  3095.     
  3096.     (set-module-name! m 'duplicate-handlers)
  3097.     (set-module-kind! m 'interface)
  3098.     (module-define! m 'check check)
  3099.     (module-define! m 'warn warn)
  3100.     (module-define! m 'replace replace)
  3101.     (module-define! m 'warn-override-core warn-override-core)
  3102.     (module-define! m 'first first)
  3103.     (module-define! m 'last last)
  3104.     (module-define! m 'merge-generics noop)
  3105.     (module-define! m 'merge-accessors noop)
  3106.     m))
  3107.  
  3108. (define (lookup-duplicates-handlers handler-names)
  3109.   (and handler-names
  3110.        (map (lambda (handler-name)
  3111.           (or (module-symbol-local-binding
  3112.            duplicate-handlers handler-name #f)
  3113.           (error "invalid duplicate handler name:"
  3114.              handler-name)))
  3115.         (if (list? handler-names)
  3116.         handler-names
  3117.         (list handler-names)))))
  3118.  
  3119. (define default-duplicate-binding-procedures
  3120.   (make-mutable-parameter #f))
  3121.  
  3122. (define default-duplicate-binding-handler
  3123.   (make-mutable-parameter '(replace warn-override-core warn last)
  3124.               (lambda (handler-names)
  3125.                 (default-duplicate-binding-procedures
  3126.                   (lookup-duplicates-handlers handler-names))
  3127.                 handler-names)))
  3128.  
  3129. (define (make-duplicates-interface)
  3130.   (let ((m (make-module)))
  3131.     (set-module-kind! m 'custom-interface)
  3132.     (set-module-name! m 'duplicates)
  3133.     m))
  3134.  
  3135. (define (process-duplicates module interface)
  3136.   (let* ((duplicates-handlers (or (module-duplicates-handlers module)
  3137.                   (default-duplicate-binding-procedures)))
  3138.      (duplicates-interface (module-duplicates-interface module)))
  3139.     (module-for-each
  3140.      (lambda (name var)
  3141.        (cond ((module-import-interface module name)
  3142.           =>
  3143.           (lambda (prev-interface)
  3144.         (let ((var1 (module-local-variable prev-interface name))
  3145.               (var2 (module-local-variable interface name)))
  3146.           (if (not (eq? var1 var2))
  3147.               (begin
  3148.             (if (not duplicates-interface)
  3149.                 (begin
  3150.                   (set! duplicates-interface
  3151.                     (make-duplicates-interface))
  3152.                   (set-module-duplicates-interface!
  3153.                    module
  3154.                    duplicates-interface)))
  3155.             (let* ((var (module-local-variable duplicates-interface
  3156.                                name))
  3157.                    (val (and var
  3158.                      (variable-bound? var)
  3159.                      (variable-ref var))))
  3160.               (let loop ((duplicates-handlers duplicates-handlers))
  3161.                 (cond ((null? duplicates-handlers))
  3162.                   (((car duplicates-handlers)
  3163.                     module
  3164.                     name
  3165.                     prev-interface
  3166.                     (and (variable-bound? var1)
  3167.                      (variable-ref var1))
  3168.                     interface
  3169.                     (and (variable-bound? var2)
  3170.                      (variable-ref var2))
  3171.                     var
  3172.                     val)
  3173.                    =>
  3174.                    (lambda (var)
  3175.                      (module-add! duplicates-interface name var)))
  3176.                   (else
  3177.                    (loop (cdr duplicates-handlers)))))))))))))
  3178.      interface)))
  3179.  
  3180.  
  3181.  
  3182. ;;; {`cond-expand' for SRFI-0 support.}
  3183. ;;;
  3184. ;;; This syntactic form expands into different commands or
  3185. ;;; definitions, depending on the features provided by the Scheme
  3186. ;;; implementation.
  3187. ;;;
  3188. ;;; Syntax:
  3189. ;;;
  3190. ;;; <cond-expand>
  3191. ;;;   --> (cond-expand <cond-expand-clause>+)
  3192. ;;;     | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
  3193. ;;; <cond-expand-clause>
  3194. ;;;   --> (<feature-requirement> <command-or-definition>*)
  3195. ;;; <feature-requirement>
  3196. ;;;   --> <feature-identifier>
  3197. ;;;     | (and <feature-requirement>*)
  3198. ;;;     | (or <feature-requirement>*)
  3199. ;;;     | (not <feature-requirement>)
  3200. ;;; <feature-identifier>
  3201. ;;;   --> <a symbol which is the name or alias of a SRFI>
  3202. ;;;
  3203. ;;; Additionally, this implementation provides the
  3204. ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
  3205. ;;; determine the implementation type and the supported standard.
  3206. ;;;
  3207. ;;; Currently, the following feature identifiers are supported:
  3208. ;;;
  3209. ;;;   guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
  3210. ;;;
  3211. ;;; Remember to update the features list when adding more SRFIs.
  3212. ;;;
  3213.  
  3214. (define %cond-expand-features
  3215.   ;; Adjust the above comment when changing this.
  3216.   '(guile
  3217.     r5rs
  3218.     srfi-0   ;; cond-expand itself
  3219.     srfi-4   ;; homogenous numeric vectors
  3220.     srfi-6   ;; open-input-string etc, in the guile core
  3221.     srfi-13  ;; string library
  3222.     srfi-14  ;; character sets
  3223.     srfi-55  ;; require-extension
  3224.     srfi-61  ;; general cond clause
  3225.     ))
  3226.  
  3227. ;; This table maps module public interfaces to the list of features.
  3228. ;;
  3229. (define %cond-expand-table (make-hash-table 31))
  3230.  
  3231. ;; Add one or more features to the `cond-expand' feature list of the
  3232. ;; module `module'.
  3233. ;;
  3234. (define (cond-expand-provide module features)
  3235.   (let ((mod (module-public-interface module)))
  3236.     (and mod
  3237.      (hashq-set! %cond-expand-table mod
  3238.              (append (hashq-ref %cond-expand-table mod '())
  3239.                  features)))))
  3240.  
  3241. (define cond-expand
  3242.   (procedure->memoizing-macro
  3243.    (lambda (exp env)
  3244.      (let ((clauses (cdr exp))
  3245.        (syntax-error (lambda (cl)
  3246.                (error "invalid clause in `cond-expand'" cl))))
  3247.        (letrec
  3248.        ((test-clause
  3249.          (lambda (clause)
  3250.            (cond
  3251.         ((symbol? clause)
  3252.          (or (memq clause %cond-expand-features)
  3253.              (let lp ((uses (module-uses (env-module env))))
  3254.                (if (pair? uses)
  3255.                (or (memq clause
  3256.                      (hashq-ref %cond-expand-table
  3257.                         (car uses) '()))
  3258.                    (lp (cdr uses)))
  3259.                #f))))
  3260.         ((pair? clause)
  3261.          (cond
  3262.           ((eq? 'and (car clause))
  3263.            (let lp ((l (cdr clause)))
  3264.              (cond ((null? l)
  3265.                 #t)
  3266.                ((pair? l)
  3267.                 (and (test-clause (car l)) (lp (cdr l))))
  3268.                (else
  3269.                 (syntax-error clause)))))
  3270.           ((eq? 'or (car clause))
  3271.            (let lp ((l (cdr clause)))
  3272.              (cond ((null? l)
  3273.                 #f)
  3274.                ((pair? l)
  3275.                 (or (test-clause (car l)) (lp (cdr l))))
  3276.                (else
  3277.                 (syntax-error clause)))))
  3278.           ((eq? 'not (car clause))
  3279.            (cond ((not (pair? (cdr clause)))
  3280.               (syntax-error clause))
  3281.              ((pair? (cddr clause))
  3282.               ((syntax-error clause))))
  3283.            (not (test-clause (cadr clause))))
  3284.           (else
  3285.            (syntax-error clause))))
  3286.         (else
  3287.          (syntax-error clause))))))
  3288.      (let lp ((c clauses))
  3289.        (cond
  3290.         ((null? c)
  3291.          (error "Unfulfilled `cond-expand'"))
  3292.         ((not (pair? c))
  3293.          (syntax-error c))
  3294.         ((not (pair? (car c)))
  3295.          (syntax-error (car c)))
  3296.         ((test-clause (caar c))
  3297.          `(begin ,@(cdar c)))
  3298.         ((eq? (caar c) 'else)
  3299.          (if (pair? (cdr c))
  3300.          (syntax-error c))
  3301.          `(begin ,@(cdar c)))
  3302.         (else
  3303.          (lp (cdr c))))))))))
  3304.  
  3305. ;; This procedure gets called from the startup code with a list of
  3306. ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
  3307. ;;
  3308. (define (use-srfis srfis)
  3309.   (process-use-modules
  3310.    (map (lambda (num)
  3311.       (list (list 'srfi (string->symbol
  3312.                  (string-append "srfi-" (number->string num))))))
  3313.     srfis)))
  3314.  
  3315.  
  3316.  
  3317. ;;; srfi-55: require-extension
  3318. ;;;
  3319.  
  3320. (define-macro (require-extension extension-spec)
  3321.   ;; This macro only handles the srfi extension, which, at present, is
  3322.   ;; the only one defined by the standard.
  3323.   (if (not (pair? extension-spec))
  3324.       (scm-error 'wrong-type-arg "require-extension"
  3325.                  "Not an extension: ~S" (list extension-spec) #f))
  3326.   (let ((extension (car extension-spec))
  3327.         (extension-args (cdr extension-spec)))
  3328.     (case extension
  3329.       ((srfi)
  3330.        (let ((use-list '()))
  3331.          (for-each
  3332.           (lambda (i)
  3333.             (if (not (integer? i))
  3334.                 (scm-error 'wrong-type-arg "require-extension"
  3335.                            "Invalid srfi name: ~S" (list i) #f))
  3336.             (let ((srfi-sym (string->symbol
  3337.                              (string-append "srfi-" (number->string i)))))
  3338.               (if (not (memq srfi-sym %cond-expand-features))
  3339.                   (set! use-list (cons `(use-modules (srfi ,srfi-sym))
  3340.                                        use-list)))))
  3341.           extension-args)
  3342.          (if (pair? use-list)
  3343.              ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
  3344.              `(begin ,@(reverse! use-list)))))
  3345.       (else
  3346.        (scm-error
  3347.         'wrong-type-arg "require-extension"
  3348.         "Not a recognized extension type: ~S" (list extension) #f)))))
  3349.  
  3350.  
  3351.  
  3352. ;;; {Load emacs interface support if emacs option is given.}
  3353. ;;;
  3354.  
  3355. (define (named-module-use! user usee)
  3356.   (module-use! (resolve-module user) (resolve-interface usee)))
  3357.  
  3358. (define (load-emacs-interface)
  3359.   (and (provided? 'debug-extensions)
  3360.        (debug-enable 'backtrace))
  3361.   (named-module-use! '(guile-user) '(ice-9 emacs)))
  3362.  
  3363.  
  3364.  
  3365. (define using-readline?
  3366.   (let ((using-readline? (make-fluid)))
  3367.      (make-procedure-with-setter
  3368.       (lambda () (fluid-ref using-readline?))
  3369.       (lambda (v) (fluid-set! using-readline? v)))))
  3370.  
  3371. (define (top-repl)
  3372.   (let ((guile-user-module (resolve-module '(guile-user))))
  3373.  
  3374.     ;; Load emacs interface support if emacs option is given.
  3375.     (if (and (module-defined? guile-user-module 'use-emacs-interface)
  3376.          (module-ref guile-user-module 'use-emacs-interface))
  3377.     (load-emacs-interface))
  3378.  
  3379.     ;; Use some convenient modules (in reverse order)
  3380.  
  3381.     (set-current-module guile-user-module)
  3382.     (process-use-modules 
  3383.      (append
  3384.       '(((ice-9 r5rs))
  3385.     ((ice-9 session))
  3386.     ((ice-9 debug)))
  3387.       (if (provided? 'regex)
  3388.       '(((ice-9 regex)))
  3389.       '())
  3390.       (if (provided? 'threads)
  3391.       '(((ice-9 threads)))
  3392.       '())))
  3393.     ;; load debugger on demand
  3394.     (module-use! guile-user-module
  3395.          (make-autoload-interface guile-user-module
  3396.                       '(ice-9 debugger) '(debug)))
  3397.  
  3398.  
  3399.     ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
  3400.     ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
  3401.     ;; no effect.
  3402.     (let ((old-handlers #f)
  3403.       (signals (if (provided? 'posix)
  3404.                `((,SIGINT . "User interrupt")
  3405.              (,SIGFPE . "Arithmetic error")
  3406.              (,SIGSEGV
  3407.               . "Bad memory access (Segmentation violation)"))
  3408.                '())))
  3409.       ;; no SIGBUS on mingw
  3410.       (if (defined? 'SIGBUS)
  3411.       (set! signals (acons SIGBUS "Bad memory access (bus error)"
  3412.                    signals)))
  3413.  
  3414.       (dynamic-wind
  3415.  
  3416.       ;; call at entry
  3417.       (lambda ()
  3418.         (let ((make-handler (lambda (msg)
  3419.                   (lambda (sig)
  3420.                     ;; Make a backup copy of the stack
  3421.                     (fluid-set! before-signal-stack
  3422.                         (fluid-ref the-last-stack))
  3423.                     (save-stack 2)
  3424.                     (scm-error 'signal
  3425.                            #f
  3426.                            msg
  3427.                            #f
  3428.                            (list sig))))))
  3429.           (set! old-handlers
  3430.             (map (lambda (sig-msg)
  3431.                (sigaction (car sig-msg)
  3432.                       (make-handler (cdr sig-msg))))
  3433.              signals))))
  3434.  
  3435.       ;; the protected thunk.
  3436.       (lambda ()
  3437.         (let ((status (scm-style-repl)))
  3438.           (run-hook exit-hook)
  3439.           status))
  3440.  
  3441.       ;; call at exit.
  3442.       (lambda ()
  3443.         (map (lambda (sig-msg old-handler)
  3444.            (if (not (car old-handler))
  3445.                ;; restore original C handler.
  3446.                (sigaction (car sig-msg) #f)
  3447.                ;; restore Scheme handler, SIG_IGN or SIG_DFL.
  3448.                (sigaction (car sig-msg)
  3449.                   (car old-handler)
  3450.                   (cdr old-handler))))
  3451.          signals old-handlers))))))
  3452.  
  3453. ;;; This hook is run at the very end of an interactive session.
  3454. ;;;
  3455. (define exit-hook (make-hook))
  3456.  
  3457.  
  3458.  
  3459. ;;; {Deprecated stuff}
  3460. ;;;
  3461.  
  3462. (begin-deprecated
  3463.  (define (feature? sym)
  3464.    (issue-deprecation-warning
  3465.     "`feature?' is deprecated.  Use `provided?' instead.")
  3466.    (provided? sym)))
  3467.  
  3468. (begin-deprecated
  3469.  (primitive-load-path "ice-9/deprecated.scm"))
  3470.  
  3471.  
  3472.  
  3473. ;;; Place the user in the guile-user module.
  3474. ;;;
  3475.  
  3476. (define-module (guile-user))
  3477.  
  3478. ;;; boot-9.scm ends here
  3479.